In the previous project, the calculator program was developed and the game player. These two programs share a common feature: they include several digital buttons of the control calculator with similar functions 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 an ASP. NET control array. The following is a simple implementation of the Button array in ASP. NET:
- Button [] btns =NewButton [9];
-
- Private VoidShowButtonArray ()
- {
- For(IntI = 0; I <9; I ++)
- {
- Btns [I] =NewButton ();// This sentence is often ignored by beginners. Note that you must create an object instance!
- Btns [I]. Location =NewSystem. Drawing. Point (100 + 50 * (I % 3), 100 + 50*(I/3 ));
- Btns [I]. Name ="BtnTest";
- Btns [I]. Size =NewSystem. Drawing. Size (48, 48 );
- Btns [I]. Text = I. ToString ();
- Btns [I]. Click + =NewSystem. EventHandler (This. Btns_Click );// Unified event handling
- This. Controls. Add (btns [I]);// Display controls on the form
- }
- }
-
- Private VoidBtns_Click (ObjectSender, System. EventArgs e)
- {
- MessageBox. Show (Button) sender). Text +"Was clicked! ");// Controls that use sender to determine the event to be triggered
- }
-
- Private VoidForm1_Load (ObjectSender, System. EventArgs e)
- {
- ShowButtonArray ();
- }
In fact, you only need to read the "Code generated by the Windows Form Designer" and you will be able to understand it soon. create and present ASP. Net. NET control array process to write a simple ASP. NET control array. In the above example, the position of the Button is calculated by a formula. In actual use, you can flexibly change it 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 an ASP. NET 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.
- Add shortcut menu for ASP. NET Control
- Write unit test (ViewState) for Asp.net controls)
- There are two points worth noting during ASP. NET development.
- Which of ASP. NET, JSP, and PHP is better?
- Analysis of ASP. NET page request principles