DOTNETRemoves the control array, which makes it a habit to useProgramThe staff is very uncomfortable. Is there any way to implement the control array function? The answer is yes.
As we all know, the main two advantages of a control array are that it can enclose values cyclically and respond to the same event. This greatly simplifiesCode. The following is an example based on these two aspects.
Create a project and add five Textbox (textbox1. .. textbox5) and two buttons (button1 and button2) to the form ).
1.Loop Value
In general, there are two implementation methods:
1.1Defines a dynamic control array. Because DOTNET supports dynamic control arrays, We can attach the designed controls to dynamic arrays so that we can use them at will. The Code is as follows:
Private void button#click (Object sender, system. eventargs E)
{
Textbox [] mytextbox = new textbox [5];
Mytextbox [0] = textbox1;
Mytextbox [1] = textbox2;
Mytextbox [2] = textbox3;
Mytextbox [3] = textbox4;
Mytextbox [4] = textbox5;
for (INT I = 0; I <5; I ++)
{< br> mytextbox [I]. TEXT = "";
}< BR >}
1.2 Use the control array of the form. The controls in the form are included in the control, so they can be differentiated based on their categories. The Code is as follows:
private void button2_click (Object sender, system. eventargs e)
{< br> foreach (control mycontrols in this. controls)
{< br> If (mycontrols. tostring (). indexof ("textbox")> 0)
{< br> mycontrols. TEXT = "";
}
}
}
2.Event Response
Let the controls in the array respond to the same corresponding event, and distinguish them by unique identifiers in the array. In the following example, five textbox events are responded to the same keypress event.
Customize a control event-textbox_keypress. The Code is as follows:
Private void textbox_keypress (Object sender, system. Windows. Forms. keypresseventargs E)
{
textbox box = (textbox) sender;
MessageBox. show (this, "you choose" + box. name + "and you keypress" + E. keychar. tostring (), "try", messageboxbuttons. OK);
}
Select textbox1, press F4 to display its property page, and select the "events" button (that is, the little lightning) to list all textbox1 events, in keypress, write the event name textbox_keypress. In this way, when textbox1 generates a keypress event, it corresponds to the Custom Event textbox_keypress. Similarly, other textbox controls are configured with the above attributes. In this way, the five textbox responds to a keypress event at the same timeObject senderCan be differentiated. In this way, the array effect is achieved.
The above is based on my own experience. If you have other good methods, you are welcome to discuss it.