Matthew A. stoecker
Visual Studio team
Microsoft Corporation
January 2002
Summary: This article describes how to use Visual Basic. NET and 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. Visual Basic. NET and C #
It 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:
'Visual basic pseudoCode
Mycontrol (myindex). myproperty = myvalue
Mycontrol (myindex + 1). mymethod
// C # pseudocode
Mycontrol [myindex]. myproperty = myvalue;
Mycontrol [myindex + 1]. mymethod
- Process a single eventProgramProcess events of multiple controls and retrieve and use the indexes of these events, as shown in the following example:
'Visual basic pseudocode
Private sub mycontrol_click (sender as object, e as eventargs)
MessageBox. Show ("You have clicked mycontrol No "&_
Mycontrol. Index)
End sub
// C # pseudocode
Private void mycontrol_click (system. Object sender, system. eventargs E)
{
MessageBox. Show ("You have clicked mycontrol No." +
Mycontrol. Index );
}
-
- Add or delete controls dynamically at runtime, as shown below:
'Visual basic pseudocode
Dim I as integer
For I = 1 to 5
'Insert code to create a control and assign a value to the property.
Next I
// C # pseudocode
For (INT I = 1; I <6; I ++)
{
// Insert code to create a control and assign a value to the property.
}
Visual Basic. NET and C # Allow 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
- InFile(File) menu, pointingNew(New), and then selectProject(Project) to openNew project(New project) dialog box.
- Select from the Visual Basic or Visual C # project listWindows Application(Windows Application) Project template, and inNameIn the (name) box, typeButtonarrayproject.
- SlaveFile(File) menu, selectSave all(Save all) to save the project.
Implementation set
Buttonarray
Class to support and organize control arrays by implementing collections. 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 createSystem. Collections. collectionbase(Classes in the. NET Framework provide the many functions required by the Set), and provide the required functions.
Create an inherited class
- SlaveProject(Project), selectAdd class(Add a class ).
- Name the classButtonarray. VBOrButtonarray. CS.
The Code Editor containing the class will be opened ).
- In the class declaration, specify this class from the. NET FrameworkSystem. Collections. collectionbaseClass.
'Visual basic
Public class buttonarray
Inherits system. Collections. collectionbase
End Class
// C #
Public class buttonarray: system. Collections. collectionbase
{
// The code added by the designer is omitted.
}
System. Collections. collectionbaseClass provides many functions required by the set. IncludingListObject (the object contained in the trace set ),CountAttribute (maintain the total number of objects in the current set) andRemoveatMethod (delete 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
The first method that must be implemented in the set isAddnewbutton
. 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
This method will:
- Create button.
- Add the new button to the internal list and
Hostform
Control Set of the referenced form.
- Set the initial attributes, includingTagSet the attribute to the index of the button. You can add code in this section to set other properties of the control.
You must also create a constructor (the method to run when the component is instantiated) for settingHostform
Field Value, and you only need to create a new instance of the control array class, you can automatically add a new button in the form. You can complete this task in the following ways.
Create Constructor
- Create a class constructor.
'Visual basic
Public sub new (byval host as system. Windows. Forms. Form)
Hostform = Host
Me. addnewbutton ()
End sub
// 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 specifiesHostform
And then callAddnewbutton
Method to add a new button in 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 for execution.
This operation. You will create a default property (Visual Basic) or Index Program
(C #) returns a reference to a specific button Based on the index. This also enables you to use the typical control array through programmingMybuttonarray (myindex)
Syntax.
Create default properties
- Add the following code to the component.
'Visual basic
Default public readonly property item (byval index as integer) _
System. Windows. Forms. Button
Get
Return ctype (Me. List. Item (INDEX), system. Windows. Forms. button)
End get
End Property
// 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 mustListObject and formControlsDelete the set.
Remove Method
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.
'Visual basic
Public sub clickhandler (byval sender as object, byval e _
System. eventargs)
MessageBox. Show ("You have clicked the button" & ctype (sender ,_
Button). Tag, string ))
End sub
// 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, which is stored inTagThe index in the property to indicate what 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
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-clickForm1And selectView designer(View designer ).
Will open the includeForm1.
-
- 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 |
Add button |
Button2 |
Btnremove |
Delete button |
-
- In Solution Explorer, right-clickForm1And selectView code(View the Code ).
The Code Editor containing form1 will be opened ).
-
- In the form1 class declaration, declare the control array object.
'Visual basic
'Declare a new buttonarray object.
Dim mycontrolarray as buttonarray
// C #
// Declare a new buttonarray object.
Buttonarray mycontrolarray;
- In the form constructor, add the following code before the end of the method:
'Visual basic
Mycontrolarray = new buttonarray (me)
// C #
Mycontrolarray = new buttonarray (this );
This statement creates a newButtonarray
Object. Parameters (MeOrThis) Will reference to create a newButtonarray
And will become the form for placing the button array.
-
- In Solution Explorer, right-clickForm1And selectView designer(View designer ).
-
- In the designer, double-clickBtnaddTo openBtnadd_clickEvent code editor ).
- InBtnadd_clickMethod, add code to call
Mycontrolarray
OfAddnewbutton
Method:'Visual basic
'Call the addnewbutton method of mycontrolarray.
Mycontrolarray. addnewbutton ()
'Change the backcolor attribute of Button 0.
Mycontrolarray (0). backcolor = system. Drawing. color. Red
// 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-clickForm1And selectView designer(View designer ).
-
- In the designer, double-clickBtnremoveTo openBtnremove_clickEvent code editor ).
- InBtnremove_clickMethod, add the following code:
'Visual basic
'Call the Remove Method of mycontrolarray.
Mycontrolarray. Remove ()
// C #
// Call the Remove Method of mycontrolarray.
Mycontrolarray. Remove ();
-
- Save the project.
Test Item
- SlaveDebugIn the (Debug) menu, selectStart(START ).
Will openForm1Contains three buttons markedAdd button(Add button ),Remove button(Delete button) andButton 1(Button 1 ).
- ClickButton 1(Button 1 ).
Note: a message box is displayed, with the index correctly displayed.
- Click several timesAdd button(Add button) button.
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,Button 0The color of (Button 0) has changed to red, becauseBtnadd_clickThe following rows in the event result in:
Mycontrolarray (0). backcolor = system. Drawing. color. Red
- Click several timesRemove button(Delete button) button.
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 againAdd button(Add button) button.
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.