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)