One of my colleagues is working on a calculator. Program Another student is playing the game. 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 . 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)
{
Showbuttonarray ();
}
In fact, as long as you read the "Code generated by the Windows Form Designer", you will soon be able to understand the process of creating and rendering controls in. net, so as to write a simple control array. In the above example, the position of the button is calculated by a formula. In actual use, the button can be flexibly changed as needed (such as the numeric button of the calculator, 1 ~ 9 It can be calculated using the formula, and 0 can be specially processed using statements such as if ). At the same time, it is worth noting that the unified processing of the event: In the btns_click function, the sender is used to determine the control to stimulate the event.
If necessary, you can encapsulate the control array into a class and add some functional code to facilitate flexible use. You can even make some custom controls into array classes to implement more complex functions.