visual| Create | controls | Arrays in Visual Basic. NET to create a control array
Brief introduction
Arrays provide a convenient way to use groups of controls that share common functionality. For example, a control group can be used to display related data, or to provide related actions when clicked. Visual Basic. NET does not natively support creating control arrays, but you can programmatically copy the full functionality of the control array. This article will guide you through creating a simple component that replicates the functionality of the control array.
Some of the useful uses of the control array are as follows:
By indexing access to a collection of controls with the same name, you can retrieve and set properties by number, and traverse all the controls in the array. The typical syntax for this operation is as follows:
' Visual Basic pseudo code
MyControl (Myindex). MyProperty = myvalue
MyControl (Myindex + 1). MyMethod
Use a single event handler to handle events for multiple controls, retrieving and using the indexes in these events, as shown in the following example:
' Visual Basic pseudo code
Private Sub Mycontrol_click (sender as Object, E as EventArgs)
MessageBox.Show ("You have clicked MyControl Number" & _
Mycontrol.index)
End Sub
Dynamically add or remove controls at run time, as follows:
' Visual Basic pseudo code
Dim I as Integer
For i = 1 to 5
' Inserts code to create the control and assign a value to the property.
Next I
Visual Basic. NET allows you to replicate some of these features, such as using agents to bind events in multiple controls to a single event handler. However, it may be more convenient to incorporate this functionality into a single dynamic, manageable component. In this article, we will create components that use the following:
A collection of index and sort controls. The button collection will be used for demonstration.
Handles the event handlers for the click events from the derived button.
Code that allows the control and its members to be referenced by index.
Dynamically add and remove code for controls in a form.
Premise
Familiar with components and their working principles.
Have a better understanding of polymorphism. For more information, see Polymorphism in Components (English).
Learn about Visual Basic. NET syntax.
Create a project
In this section, we will create and name the project and add a class to the project. The class encapsulates the code that implements the control array.
Creating Buttonarrayproject and Buttonarray components
On the File menu, point to New (new), and then select Project to open the New Project dialog box.
Select the Windows application (Windows application) project template from the Visual Basic project list and type Buttonarrayproject in the Name box.
From the File menu, select Save All to save the project.
Implementing a Collection
The Buttonarray class completes the task of supporting and organizing the array of controls by implementing the collection. A collection is an object that contains a list of indexed object variables, as well as methods for adding, deleting, or manipulating objects in the collection. In this section, we will create classes that inherit from the System.Collections.CollectionBase (the classes in the. NET framework, which provide many of the functionality required by the collection), and implement the methods that provide the required functionality.
To create an inherited class
From the Project menu, select Add Class (Add classes).
Name the class as Buttonarray.vb or ButtonArray.cs accordingly.
The code Editor that contains the class is opened.
In the class declaration, specify that this class is inherited from the System.Collections.CollectionBase class of the. NET Framework.
' Visual Basic
Public Class Buttonarray
Inherits System.Collections.CollectionBase
End Class
The System.Collections.CollectionBase class provides many of the features required by the collection. This includes the List object (the objects that the Tracking collection contains), the Count property (the total number of objects in the current collection), and the RemoveAt method (the object is deleted by a specific index). These features are used when implementing a collection of control arrays.
Because all control array components are associated with a form, you need to add a field to keep a reference to the form. By creating a dedicated read-only field to keep the reference, you can ensure that each control array component is associated with only one form.
To add a dedicated read-only field to a component
Add the following line directly to the class declaration:
' Visual Basic
Private ReadOnly Hostform as System.Windows.Forms.Form
The first method that must be implemented in the collection is Addnewbutton. This method creates a new button control and adds it to the form you want. You also need to use this method to set the initial properties of the New button.
Implement Addnewbutton method
In the code Editor that contains the Buttonarray class, type the following code:
Public Sub Addnewbutton ()
' Creates a new instance of the Button class.
Dim Abutton as New System.Windows.Forms.Button ()
' Adds a button to the internal list of collections.
ME.LIST.ADD (Abutton)
' Add a button to the Hostform field
' The control collection of the referenced form.
HOSTFORM.CONTROLS.ADD (Abutton)
' Sets the initial properties of the button object.
Abutton.top = Count * 25
Abutton.left = 100
Abutton.tag = Me.count
Abutton.text = "button" & Me.Count.ToString
End Sub
This method will:
Create a New button.
Adds a new button to the internal list and to the control collection of the form referenced by Hostform.
Sets the initial properties, including setting the Tag property 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 that runs when the component is instantiated), set the value of the Hostform field, and automatically add a new button to the form whenever you create a new instance of the control array class. You can complete this task in the following ways.
Creating constructors
Creates a constructor for the class.
' Visual Basic
Public Sub New (ByVal host as System.Windows.Forms.Form)
Hostform = Host
Me.addnewbutton ()
End Sub
The constructor requires a parameter, the form where the button array is placed. It specifies the value that is provided to the Hostform field, and then calls the class's Addnewbutton method to add a new button to the form.
Exposing control arrays
You have created a way to create and trace controls in an array, and you now need to expose them to other developers. You can use a property to perform this operation. You will create a default property (Visual Basic) or an index program (C #) that returns a reference to a specific button based on the index. This also enables you to programmatically use the typical Mybuttonarray (myindex) syntax of the control array.
Create Default Properties
Add the following code to the component.
' Visual Basic
Default Public ReadOnly Property Item (ByVal Index as Integer) as _
System.Windows.Forms.Button
Get
Return CType (Me.List.Item (Index), System.Windows.Forms.Button)
End Get
End Property
Implementing the Remove Method
You have created the properties required to expose the buttons in the array, and you can now implement the mechanism for removing the buttons from the array. To remove a button from an array, you must remove it from the collection's internal List object and from the Controls collection of the form.
Implementing the Remove Method
Add the following methods to the component.
' Visual Basic
Public Sub Remove ()
' Check to make sure there is a button to delete.
If me.count > 0 Then
' Remove the add to array from the host form control collection
' The last button. Note that when you access the array,
' Use of the default property.
HostForm.Controls.Remove (Me (me.count-1))
Me.List.RemoveAt (me.count-1)
End If
End Sub
Create a public event handler
The final step is to create an event handler to handle the public events of the array. In this case, we'll create a way to handle the button's click event, 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 As _
System.EventArgs)
MessageBox.Show ("You have clicked Button" & CType (CType sender, _
Button). Tag, String))
End Sub
This method displays a message box that indicates what button was clicked by retrieving the index stored in the Tag property of the button. Note that the signature of this method is the same as the signature of the event it will handle, as required by the event handler.
You also need to associate an event with an event handler.
Associate an event with an event handler
Add the following code in the Addnewbutton method.
' Visual Basic
AddHandler Abutton.click, AddressOf ClickHandler
Test Project
After you complete the project, you need to create an application to test the functionality of the component.
To create a test application
In Solution Explorer (Solution Explorer), right-click Form1 and select View Designer from the shortcut menu (View Designer).
The designer that contains the Form1 will open.
From the Toolbox, add two buttons to the form.
Reposition these buttons to the right of the form.
Set the properties of the button as shown below. Button Name text
Button1 btnadd Add button
Button2 btnremove Delete button
In Solution Explorer (Solution Explorer), right-click Form1 and select View Code from the shortcut menu.
The code Editor that contains Form1 is opened (the Codes editor).
In the Form1 class declaration, declare the control array object.
' Visual Basic
' Declares a new Buttonarray object.
Dim Mycontrolarray as Buttonarray
In the form's 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 new Buttonarray object. The parameter (Me or this) refers to the form that creates the new Buttonarray and becomes the form where the button array is placed.
In Solution Explorer (Solution Explorer), right-click Form1 and select View Designer from the shortcut menu (View Designer).
In the designer, double-click Btnadd to open the code Editor that contains the btnAdd_Click event.
In the btnAdd_Click method, add code to invoke the Mycontrolarray Addnewbutton method:
' Visual Basic
' Call the Mycontrolarray Addnewbutton method.
Mycontrolarray.addnewbutton ()
' Change the BackColor property of button 0.
Mycontrolarray (0). BackColor = System.Drawing.Color.Red
In Solution Explorer (Solution Explorer), right-click Form1 and select View Designer from the shortcut menu (View Designer).
In the designer, double-click Btnremove to open the code Editor that contains the Btnremove_click event.
In the Btnremove_click method, add the following code:
' Visual Basic
' Invokes the Mycontrolarray Remove method.
Mycontrolarray.remove ()
Save the project.
Test Project
From the Debug (Debug) menu, select Start.
The Form1 opens with three buttons, labeled Add button (add), remove button (delete), and button 1 (1).
Click the button 1 (Button 1).
Notice that the screen displays a message box with the index correctly displayed.
Click the Add button (add buttons) button several times.
Each time you click, a New button is added to the form. Clicking each new button displays a message box that correctly reports the index of the button. Also note that the color of button 0 (buttons 0) has changed to red because of the following line in the btnAdd_Click event:
Mycontrolarray (0). BackColor = System.Drawing.Color.Red
Click the Remove button (remove buttons) button several times.
Each click Deletes a button from the form.
Click this button until you delete all the buttons on the left side of the form.
Click the Add button again.
The button is added to the form again and is numbered with the correct index.
Summarize
This article demonstrates how to create a component that encapsulates the functionality of a control array. This includes how to create methods to dynamically add and remove controls on a form, and expose objects by default properties or indexing programs. Because all of the functionality is implemented, you can extend the control array by writing custom code for the component.
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.