On the dialog side, you would define the following:
//The EventArgs derived class that contains a single extra property, the
name of the new item
public class NewItemEventArgs : EventArgs
{
private string newItemName;
public string NewItemName
{
get
{
return newItemName;
}
}
public NewItemEventArgs( string newItemName )
{
this.newItemName = newItemName;
}
}
//The delegate defining the signature of the event
public delegate void NewItemEventHandler(object sender, NewItemEventArgs
e);
//The actual event that is subscribed to and fired
public event NewItemEventHandler NewItem;
//What the dialog form calls when it wants to raise the event.
private void OnNewItem(string newItemName)
{
if( NewItem != null )
{
NewItem(this, new NewItemEventArgs( newItemName ) );
}
}
On the main form side, when you want to create the new form, you would do
the following:
DialogForm f = new DialogForm();
f.NewItem +=new DialogForm.NewItemEventHandler(f_NewItem);
f.ShowDialog();
What does all of this do? It starts by creating a new instance of the
DialogForm class, and later attaches a new NewItemEventHandler to the
NewItem
event, so that whenever the NewItem event is fired, f_NewItem is called.
Finally, the dialog is shown.
One little note, f_NewItem is quite simple as you see below in which it
gets
a reference to the NewItemEventArgs created when the event was raised,
accesses the NewItemName property and adds it to the ListBox.
private void f_NewItem(object sender, DialogForm.NewItemEventArgs e)
{
myListBox.Items.Add( e.NewItemName );
}
Back to the Dialog form real quick... how does all of that work? The
standard is that when an event is raised, it should pass an instance of
something that is or derives from the EventArgs class, in this case, we
are
using NewItemEventArgs which as noted above simply defines an extra
property.
You can easily expand on it to contain almost anything you want.
The delegate defines what the event looks like, that is to say, what
values
it is able to carry with it when it is fired.
The actual event is quite simple, simply saying that you want an event of
a
given name that uses a certain type of EventHandler (delegate).
Finally, OnNewItem which provides a safety mechanism when accessing the
handler. If you try to fire an event directly that doesn't have any
subscribers, bad things happen, and in OnNewItem we check to see if
anything
is subscribed with the != null, and if we have anything, we fire the event
by
calling it with the arguments of the sender (this) and a new instance of
NewItemEventArgs whose constructor allows it to take a string which sets
the
newItemName portion of the class.
Brendan