Sunday, March 23, 2014

Using Events and Delegates in Visual C#.NET


Here are the steps to create events and delegates in .NET.
 
STEP 1:

In the Child Control which raises the event, you should have the following:

public delegate void ZoomtoMapEventHandler(object sender, ClassQueryResultsSet CQRe);

public event ZoomtoMapEventHandler ZoomtoMapEvent;

where the ClassQueryResultsSet is as follows :

public class ClassQueryResultsSet : EventArgs
                {
                                public DataSet QueryResultsDataSet ;
                                public string QueryResultsTableName ;
                                public string KeyFieldName ;
                                public ClassQueryResultsSet()
                                {
                                                //
                                                // TODO: Add constructor logic here
                                                //
                                                QueryResultsDataSet = null ;
                                                QueryResultsTableName = null ;
                                                KeyFieldName = "" ;
                                }
                }

Also when invoking the event check for null and do it as shown below:

                                                                if (ZoomtoMapEvent != null)
                                                                {
                                                                                ZoomtoMapEvent(this, Res) ;
                                                                }
                                                                else
                                                                {
                                                                                MessageBox.Show("ZoomtoMapEvent is Null !") ;
                                                                }

STEP 2

In the MAIN PARENT Program, the event is declared like below

x.userControlQuerySingleTable1.ZoomtoMapEvent += new WindowsControlLibrarySingleTable.UserControlQuerySingleTable.ZoomtoMapEventHandler(x.ShowMaptoUser)  ;

 
Also the function into which the control should come in should have the same signature as shown below:

public void ShowMaptoUser(object o, ClassQueryResultsSet e)
{
                MessageBox.Show("Calling ok" + e.QueryResultsTableName) ;
}

Using this events and delegates will come in handy when passing information from one class to another.

Happy coding.

Cheers
Adam

All Blogs so far ...