Controls | arrays
Implementing a simple array of controls in C #
One of my classmates is doing calculator program, another classmate is doing well word chess game. The two programs have a common feature: a number of controls with similar functions (the calculator's number button and the nine drop bits of the well character). If you create these controls, you'll have to write a lot of duplicate code, which is more cumbersome to modify. A better option is to create an array of controls. 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 overlooked for beginners, notice to create an instance of the Object!
Btns[i]. Location = new System.Drawing.Point (i% 3), + * (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 Handling
This. Controls.Add (Btns[i]); Rendering controls on a form
}
}
private void Btns_click (object sender, System.EventArgs e)
{
MessageBox.Show ((Button) sender). Text + "was clicked!"); To judge a control that fires an event by sender
}
private void Form1_Load (object sender, System.EventArgs e)
{
Showbuttonarray ();
}
In fact, you can quickly understand the "code generated by the Windows forms Designer" just by looking at it. NET creates and renders a control's process, which writes out a simple array of controls. In the example above, the position of the button rendering is calculated by a formula, and in practice, it can be flexibly changed according to the need (for example, the calculator's number button, 1~9 can be calculated by formula, 0 can be used if such as the statement special processing). Also noteworthy is the uniform handling of events: in the Btns_click function, the control that fires events is judged by sender.
If necessary, you can encapsulate the array of controls into classes, plus certain functional code to make it easy to use. Even some custom controls can be made into array classes to achieve more complex functionality.