Use C # to implement a simple control array
One of my colleagues is working on a calculator program, and the other is playing a game of play. These two programs share a common feature: including several controls with similar functions (the digital buttons of the calculator and nine sub-positions of the player ). If you create these controls one by one, you have to write a large number of repeated code, which is difficult to modify. A better choice is to create a control array. The following is a simple implementation of the Button array:
Button [] btns = new Button [9];
Private void ShowButtonArray ()
{
For (int I = 0; I <9; I ++)
{
Btns [I] = new Button (); // This sentence is often ignored by beginners. Note that you must create an object instance!
Btns [I]. Location = new System. Drawing. Point (100 + 50 * (I % 3), 100 + 50*(I/3 ));
Btns [I]. Name = "btnTest ";
Btns [I]. Size = new System. Drawing. Size (48, 48 );
Btns [I]. Text = I. ToString ();
Btns [I]. Click + = new System. EventHandler (this. btns_Click); // unified event processing
This. Controls. Add (btns [I]); // render the control on the form
}
}
Private void btns_Click (object sender, System. EventArgs e)
{
MessageBox. Show (Button) sender). Text + "was clicked! "); // Controls that use sender to determine the event to be triggered
}
Private void Form1_Load (object sender, System. EventArgs e)
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