Create control array

Source: Internet
Author: User

Abstract: This article describes how to use Visual C #? . Net to create and manage control arrays.
Directory
Introduction
Prerequisites
Create a project
Implementation set
Public control array
Create a public event handler
Test Item
Summary
Introduction
Arrays provide a convenient way for control groups that use shared public functions. For example, a control group can be used to display related data or provide related operations when clicked. C # itself does not support creating control arrays, but you can use programming to copy all the functions of control arrays. This document describes how to create a simple component for copying control arrays.
Some functions of the control array are as follows:
You can use indexes to access a set of controls with the same name. You can retrieve and set properties by number and traverse all controls in the array. The typical Syntax of this operation is as follows:

// C # pseudocode
Mycontrol [myindex]. myproperty = myvalue; mycontrol [myindex + 1]. mymethod
Use a single event handler to process events of multiple controls and retrieve and use the indexes of these events, as shown in the following example:

// C # pseudocode
Private void mycontrol_click (system. Object sender, system. eventargs e)... {MessageBox. Show ("You have clicked mycontrol number" + mycontrol. Index );}
Add or delete controls dynamically at runtime, as shown below:

// C # pseudocode
For (INT I = 1; I <6; I ++)
...{
// Insert code to create a control and assign a value to the property.
}
C # allows you to copy some of these features. For example, you can use a proxy to bind events in multiple controls to a single event handler. However, it may be easier to integrate this function into a single dynamic and easy-to-manage component. In this article, we will create components that use the following content:
A set of indexes and sorting controls. The button set will be used for demonstration.
The event handler that processes the click event from the derived button.
Code that allows you to reference controls and their members through indexes.
Dynamically add and delete control code in the form.
Prerequisites
Familiar with components and their working principles.
I have some knowledge about polymorphism. For more information, see polymorphism in components ).
Understand Visual Basic. Net or C #. Net syntax.
Create a project
In this section, we create and name a project and add a class to the project. This class encapsulates the code that implements the control array.
Create the buttonarrayproject and buttonarray Components
On the File menu, point to new and select project to open the new project dialog box.
Select the windows application (Windows Application) Project template from the Visual Basic or Visual C # project list, and type the buttonarrayproject In the Name box.
From the File menu, select Save all to save the project.
Implementation set
The buttonarray class implements a set to support and organize control arrays. A set is an object that contains a list of indexed object variables and methods for adding, deleting, or operating objects in the set. In this section, we will create a class inherited from system. Collections. collectionbase (Class in the. NET framework that provides many functions required by the Set) and implement the methods that provide the required functions.
Create an inherited class
Select Add class from the project menu ).
Name the class buttonarray. VB or buttonarray. CS accordingly.
The Code Editor containing the class will be opened ).
In the class declaration, specify that this class is inherited from the system. Collections. collectionbase class of the. NET Framework.

// C #
Public class buttonarray: system. Collections. collectionbase
...{
// The code added by the designer is omitted.
}
The system. Collections. collectionbase class provides many functions required by the set. These include the list object (the object contained in the tracking Set), the Count attribute (the total number of objects in the current set is maintained), and The removeat method (deleting objects by specific index ). These functions are used to implement the control array set.
Since all the control array components must be associated with a form, you must add a field to retain reference to the form. By creating a dedicated read-only field to retain the reference, you can ensure that each control array component is associated with only one form.
Add a dedicated read-only field to the component
Add the following code directly in the class declaration:

// C #
Private readonly system. Windows. Forms. Form hostform;
The first method that must be implemented in the set is addnewbutton. This method creates a button control and adds it to the required form. You also need to use this method to set the initial attributes of the new button.
Addnewbutton Method
In code editor that contains the buttonarray class, type the following code:

// C #
Public void addnewbutton ()
...{
// Create a new instance of the button class.
System. Windows. Forms. Button abutton = new
System. Windows. Forms. Button ();
// Add the button to the internal list of the set.
This. List. Add (abutton );
// Add the button to the hostform Field
// Control set of the referenced form.
Hostform. Controls. Add (abutton );
// Set the initial attributes of the button object.
Abutton. Top = count * 25;
Abutton. Left = 100;
Abutton. Tag = This. count;
Abutton. Text = "button" + this. Count. tostring ();
}

This method will:
Create button.
Add the new button to the internal list and the control set of the form referenced by hostform.
Set the initial attribute, including setting the tag attribute as a button index. You can add code in this section to set other properties of the control.
You must also create a constructor (the method that runs when the component is instantiated) to set the value of the hostform field. You only need to create a new instance of the control array class, you can automatically add a button to the form. You can complete this task in the following ways.
Create Constructor
Create a class constructor.
-

 

// C #
// Use this constructor to replace the default constructor.
Public buttonarray (system. Windows. Forms. form host)
...{
Hostform = host;
This. addnewbutton ();
}

The constructor requires a parameter, that is, the form for placing the button array. It specifies the value provided to the hostform field, and then calls the addnewbutton method of the class to add a new button to the form.
Public control array
You have created a method to create and track controls in arrays. Now you need to make these controls public to other developers. You can use an attribute to perform this operation. You will create a default Property Index Program (C #) and return a reference to a specific button Based on the index. This also enables you to use the typical mybuttonarray (myindex) syntax of the control array programmatically.
Create default properties
Add the following code to the component.
-

 

// C #
Public System. Windows. Forms. Button this [int Index]
...{
Get
...{
Return (system. Windows. Forms. Button) This. list [Index];
}
}

Remove Method
You have created the attributes required to expose the buttons in the array. Now you can delete the buttons from the array. To delete a button from an array, you must delete it from the internal list object of the Set and the controls set of the form.
Remove Method
Add the following methods to the component.
-

 

// C #
Public void remove ()
}
// Check to ensure that the button to be deleted exists.
If (this. Count> 0)
...{
// Delete the add to array from the host Form Control Set
. Note that when accessing the Array
// Use the index.
Hostform. Controls. Remove (this [This. Count-1]);
This. List. removeat (this. Count-1 );
}
}

Create a public event handler
The last step is to create an event handler to process the public events of the array. In this example, we will create a method to process the Click Event of the button, and then add code to associate the event with the event handler.
Create a public event handler
Add the following methods to the component.

 

// C #
Public void clickhandler (Object sender, system. eventargs E)
...{
System. Windows. Forms. MessageBox. Show ("You have clicked the button" +
(String) (system. Windows. Forms. Button) sender). Tag );
}

This method displays a message box. You can retrieve the index stored in the tag attribute of the button to indicate which button is clicked. Note that the signature of this method is the same as the signature of the event to be processed, which is required by the event handler.
You also need to associate the event with the event handler.
Associate events with event handlers
Add the following code to the addnewbutton method.
"Visual Basic
Addhandler abutton. Click, addressof clickhandler

 

// C #
Abutton. Click + = new system. eventhandler (clickhandler );

Test Item
After the project is completed, you need to create an application to test the functions of the component.
Create a test application
In Solution Explorer, right-click form1 and select View designer from the shortcut menu ).
The designer that contains form1 is opened.
From the toolbox, add the two buttons to the form.
Place the buttons on the right of the form.
Set the button properties as follows. Button Name text
Button1 btnadd button
Button2 btnremove button
In Solution Explorer, right-click form1 and select view code from the shortcut menu ).
The Code Editor containing form1 will be opened ).
In the form1 class declaration, declare the control array object.
// C #
// Declare a new buttonarray object.
Buttonarray mycontrolarray;
In the form constructor, add the following code before the end of the method:
-
// C #
Mycontrolarray = new buttonarray (this );
This statement creates a new buttonarray object. The parameter (me or this) references the form for creating a new buttonarray and will become the form for placing the button array.
In Solution Explorer, right-click form1 and select View designer from the shortcut menu ).
In the designer, double-click btnadd to open the code editor containing the btnadd_click event ).
In the btnadd_click method, add code to call the addnewbutton method of mycontrolarray:
-

 

// C #
// Call the addnewbutton method of mycontrolarray.
Mycontrolarray. addnewbutton ();
// Modify the backcolor attribute of Button 0.
Mycontrolarray [0]. backcolor = system. Drawing. color. Red;

In Solution Explorer, right-click form1 and select View designer from the shortcut menu ).
In the designer, double-click btnremove to open the code editor that contains the btnremove_click event (Code Editor ).
In the btnremove_click method, add the following code:
-
// C #
// Call the Remove Method of mycontrolarray.
Mycontrolarray. Remove ();
Save the project.
Test Item
Select Start from the Debug menu ).
The form1 button will be opened, which contains three buttons marked as "Add button", "Remove button", and "button 1 ).
Click button 1 ).
Note: a message box is displayed, with the index correctly displayed.
Click the Add button several times.
Each time you click a button, a new button is added to the form. A message box is displayed when you click each new button. The index of the button is correctly reported. Note that the color of Button 0 (Button 0) has changed to red, which is caused by the following rows in the btnadd_click event:
Mycontrolarray (0). backcolor = system. Drawing. color. Red
Click the Remove button several times.
Each click will delete a button from the form.
Click this button until all the buttons on the left of the form are deleted.
Click Add button again.
The button is added to the form again and numbered with the correct index.
Summary
This article demonstrates how to create components that encapsulate the control array function. These include how to create a method to dynamically add and delete controls in the form, and how to expose objects through default properties or indexing programs. Because all functions are implemented, you can extend the control array by writing custom code of components.

Article Source: http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2007126/90838.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.