Deep understanding of components in C # programming-Events-delegates

Source: Internet
Author: User
Programming is important for understanding events in component programming, and "events" in C # is a way for a class to provide notification to customers of that class when something interesting happens. Most closely related to the event, the individual considers it a delegate. A delegate can encapsulate a method reference within a delegate object. In order to understand the component-event-entrust the relationship between the three, I use the actual example to talk about the understanding of the younger brother.

First create a Windows control project and add the following control template.



When an event is triggered, a eventargs type parameter is passed to the event-handling method, and in order to be able to pass the custom information, we can create an event argument class that inherits from EventArgs, which is defined as follows:

public class EventLoginArgs:System.EventArgs
{
public string strUserID;
public string strUserName;
public string struserpwd;
public bool Bvaild;
Public Eventloginargs (String userid,string username,string userpwd)
{
strUserID = UserID;
strUserName = UserName;
Struserpwd = userpwd;

}

Then declare two delegates, which are encapsulated in the information in the Eventloginargs and EventArgs objects, as follows:

public delegate void Userlogineventhandler (Object Sender,eventloginargs e);
public delegate void CancelEventHandler (Object Sender,eventargs e);

In an assembly, a component must provide an event interface in order for the user to customize the handling of an event. If you are inheriting only a single existing Windows control, you can overload a known method to add your own processing. You can also declare a custom event interface. If the component contains multiple controls, you should declare the event interface according to the actual needs, where I declare two custom event interfaces for the use of two buttons, as follows:

public event Userlogineventhandler Submitlogin;
public event CancelEventHandler Cancel;
protected virtual void Onsubmitlogin (Eventloginargs e)
{
if (this. Submitlogin!=null)
{
Submitlogin (this,e);
}

}
protected virtual void OnCancel (EventArgs e)
{
if (this. Cancel!=null)
{
Cancel (this,e);
}

In fact, Submitlogin is an example of Userlogineventhandler delegate, puzzling is this event trigger, pass, how to deal with the process?

In this case, the Submitlogin event is triggered by the OK button:

private void Btnok_click (object sender, System.EventArgs e)
{
if (Txtid.text!= "&&txtname.text!=" "&&txtpwd.text!=")
{
intlogintime++;
Onsubmitlogin (New Eventloginargs (Txtid.text,txtname.text,txtpwd.text));
Blogin = testuserindb (new Eventloginargs (Txtid.text,txtname.text,txtpwd.text));
MessageBox.Show ("This are the Btnok_click function!", "in Control", MessageBoxButtons.OK);
if (!blogin)
MessageBox.Show ("Login in failed!", "Login Error", MessageBoxButtons.OK);
}
Else
{
MessageBox.Show ("Your must input all items!", "Login Info", MessageBoxButtons.OK);
}
}

Note that the dialog box in this example is to help understand the process of the event, and the second example is really useful.

In the Btnok_click incident response, a simple validity check is first proposed, and the practical work should be improved. The Intlogintime variable is the number of attempts to log on. TESTUSERINDB is to determine whether the user is legitimate by searching for records in the database with known information. Because component testing is done through the client, you should create a simple and straightforward client program. This is a Windows application that adds the compiled component to the user control bar, drags it to the workspace, and adds the responder for the Submitlogin event, as follows:

private void Usercontrol1_submitlogin (object sender, Userlogin.eventloginargs e)
{
MessageBox.Show ("This was in Test form!" + Usercontrol1.blogin + "\ns Login times are
"+usercontrol1.intlogintime +" \ne ' s struserid= "+e.struserid," Test ", MessageBoxButtons.OK);
}

The following results are available to run the client at this time:

This is in Test form!
This are the process in DB
This is the Btnok_click function!

The result indicates that the Onsubmitlogin (new Eventloginargs (Txtid.text,txtname.text,txtpwd.text) in the component is executed when the Btnok button is clicked, and this method calls Submitlogin ( THIS,E), thus triggering the Submitlogin event, the Usercontrol1_submitlogin responds, so the first line is printed.

followed by the execution of TESTUSERINDB, which prints out the second line.

Finally, return to the last line of output in Btnok_click.

Note that the result is different if the Onsubmitlogin and testuserindb in the Btnok_click are swapped positions. In the second example, the position of the two is reversed, the database query is first judged, In the Submitlogin event response Usercontrol1_submitlogin, the following is the main code for example two:

public delegate void Userlogineventhandler (Object Sender,eventloginargs e);
public delegate void CancelEventHandler (Object Sender,eventargs e);

public event Userlogineventhandler Submitlogin;
public event CancelEventHandler Cancel;

protected virtual void Onsubmitlogin (Eventloginargs e)
{
if (this. Submitlogin!=null)
{
Submitlogin (this,e);
}

}
protected virtual void OnCancel (EventArgs e)
{
if (this. Cancel!=null)
Cancel (this,e);
}
public string Server
{
}
public string DataBase
{
}
public string Tableset
{
}
public string Userfordb
{
}
public string Pwdfordb
{
}

public bool Testuserindb (Eventloginargs e)
{


MessageBox.Show ("This are the process for db!", "testuserindb", MessageBoxButtons.OK);
BOOL BOK = false;
if (this.strdatabase!=null && this.strserver!=null && this.struserfordb!=null)
{
if (this.strpwdfordb==null)
This.strpwdfordb = "";

String strconnection = "server=" +this.strserver + ";d atabase=" +this.strdatabase


+"; Uid= "+this.struserfordb +"; Pwd= "+THIS.STRPWDFORDB;
String strSQL = "Select Userid,username,userpwd from" +this.strtableset+ "where"


Userid= ' "+e.struserid+" ' and Username= ' "+e.strusername +" ' and userpwd= ' "+e.struserpwd+" ";
SqlConnection conn = new SqlConnection (strconnection);
Try
{
Conn. Open ();
}
catch (SqlException ex)
{
MessageBox.Show ("The database cannot be opened!) please check the parameters.", "Error", MessageBoxButtons.OK);
return false;
}
SqlDataAdapter da = new SqlDataAdapter (Strsql,conn);
DataSet ds = new DataSet ();
Try
{
Da. Fill (Ds,this.strtableset);
}
catch (SqlException ex)
{
......
}
foreach (DataRow row in DS. Tables[this.strtableset]. Rows)
{
if (row!= null)
{
BOK = true;
}

}
.......
}
Else
{
BOK = false;
}
return BOK;
}
private void Btnok_click (object sender, System.EventArgs e)
{
if (Txtid.text!= "&&txtname.text!=" "&&txtpwd.text!=")
{
intlogintime++;
Blogin = testuserindb (new Eventloginargs (Txtid.text,txtname.text,txtpwd.text));
if (!blogin)
MessageBox.Show ("Login in failed!", "Login Error", MessageBoxButtons.OK);
Else
Onsubmitlogin (New Eventloginargs (Txtid.text,txtname.text,txtpwd.text));
}
Else
{
MessageBox.Show ("Your must input all items!", "Login Info", MessageBoxButtons.OK);
}
}

private void Btncancel_click (object sender, System.EventArgs e)
{
OnCancel (e);
}

private void Usercontrol_load (object sender, System.EventArgs e)
{
Intlogintime = 0;

}
}

public class EventLoginArgs:System.EventArgs
{
public string strUserID;
public string strUserName;
public string struserpwd;
public bool Bvaild;
Public Eventloginargs (String userid,string username,string userpwd)
{
strUserID = UserID;
strUserName = UserName;
Struserpwd = userpwd;

}
}


Its client processes are mainly as follows:

private void Usercontrol1_submitlogin (object sender, Userlogin.eventloginargs e)
{
MessageBox.Show ("This are blogin=" + Usercontrol1.blogin + "at" +usercontrol1.intlogintime + "times \ n
userid= "+e.struserid+" \ username= "+e.strusername," TestResult ", MessageBoxButtons.OK);
}
private void Form1_Load (object sender, System.EventArgs e)
{
Usercontrol1.server = "localhost";
Usercontrol1.database= "Weiwen";
Usercontrol1.tableset = "TestUser";
usercontrol1.userfordb= "SA";
Usercontrol1.pwdfordb = "sa";
}

The complete code for these two examples can be downloaded here.

Readers can refer to learning or use this component directly, but should use Microsoft SQL Server as the background database, the user table used should be userid,username,userpwd three columns, and in the client program should be related to the parameters of the initialization, The Submitlogin event return value is the number of attempts intlogintime and whether the validation was successful Blogin, refer to extension example two.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.