To create an array of controls in visual Basic. NET and Visual C #. Net

Source: Internet
Author: User
Tags arrays constructor contains count visual studio
visual| Create | controls | Arrays Create control arrays in visual Basic. NET and Visual C #. Net
Matthew A. Stoecker
Visual Studio Team
Microsoft Corporation
January 2002

Summary: This article describes how to create and manage an array of controls using visual Basic®.net and Visual c#™.net.

Directory

    • Brief introduction
    • Premise
    • Create a project
    • Implementing a Collection
    • Exposing control arrays
    • Create a public event handler
    • Test Project
    • Summarize
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 and C # do 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:
    • accesses a collection of controls with the same name by index, and 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 = Myvaluemycontrol (Myindex + 1). mymethod//C # 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//C # pseudo-code private void Mycontrol_click (System.Object sender, System.EventArgs e)     {      messagebox.show ("You have clicked MyControl number" +          mycontrol.index);    } 
    • dynamically Add or remove controls at run time, as follows:
       ' Visual Basic pseudocode Dim i As Integerfor i = 1 to 5    ' inserts code to create the control and assign a value to the property. Next i//C # pseudo code for (int i = 1; i < 6; i++) {   //Inserts code to create the control and assign a value to the property. }

Visual Basic. NET and C # allow 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.
premises
    • 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 or C #. 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
    1. On the File menu, point to New ( New), and then select Project to open the new Project dialog box.
    2. Select the Windows Application(Windows application) project template from the visual Basic or Visual C # project list and type Butto in the Name box. Narrayproject.
    3. 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 the inherited from 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 functionality you need.
to create an inherited class
    1. From the Project menu, select Add Class ( add classes).
    2. Name the class as Buttonarray.vb or ButtonArray.csaccordingly.
      The code Editor that contains the class is opened.
    3. In the class declaration, specify that this class is inherited from the System.Collections.CollectionBase class of the. NET Framework.
      ' Visual basicpublic class Buttonarray Inherits System.Collections.CollectionBaseEnd class//c#public class Buttonarray : system.collections.collectionbase{//omitted the code added by the designer. }

System.Collections.CollectionBaseclass provides many of the features required by a collection. which includes ListObject (The object that the Trace collection contains), CountProperty (maintains the total number of objects in the current collection) and RemoveAtMethod (Deletes an object 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 basicprivate ReadOnly hostform as system.windows.forms.form//c#private ReadOnly Hostform;

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)     ' adds a button to the control collection of the form referenced by Hostform field      '.    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.ToStringEnd sub//C # public void Addnewbutton () {    Creates a new instance of the Button class.    system.windows.forms.button Abutton = new        System.Windows.Forms.Button ();    //adds a button to the internal list of collections.    this. List.add (Abutton);    //adds the button to the control collection of the form referenced by the Hostform field     //.    hostform.controls.add (Abutton);    //sets the initial properties of the button object.    aButton.top = Count * 25;   abutton.left = 100;   abutton.tag = this. Count;   abutton.text = "button" + this. Count.tostring ();}

This method will:
    1. Create a New button.
    2. Adds a new button to the internal list and to the control collection of the form referenced by Hostform.
    3. 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 basicpublic 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, 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 basicdefault 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 Getend property//c#public System.Windows.Forms.Button this [int index]{get {return (System.Windows.Forms.Button).   List[index]; }}

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 start from within the collection ListObject and the form's Controlscollection to remove it.
implementing the Remove method
    • Add the following methods to the component.
      ' Visual basicpublic Sub Remove () ' checks to make sure there are buttons to delete. If me.count > 0 Then ' Removes the last button added to the array from the host form control collection.      Note the use of the ' default property ' when accessing the array. HostForm.Controls.Remove (Me (me.count-1)) Me.List.RemoveAt (me.count-1) End IfEnd sub//c#public void Remove ()}/   /Check to make sure there are buttons to delete. if (this. Count > 0) {//Deletes the last button added to the array//from the Host form control collection.      Note the use of the//index when accessing the array. HostForm.Controls.Remove (this[this.      Count-1]); This. List.removeat (this.   COUNT-1); }}
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 basicpublic Sub clickhandler (ByVal sender as Object, ByVal e As _ System.EventArgs) MessageBox.Show ("You clicked Button" & CType (CType (sender, _ Button). Tag, String)) end sub//c#public void ClickHandler (Object sender, System.EventArgs e) {system.windows.forms.messagebox.s How ("You have clicked the button" + (String) (System.Windows.Forms.Button) sender). TAG);

      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 basicaddhandler abutton.click, AddressOf clickhandler//C#abutton.click + = new System.EventHandler ( 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
  1. In Solution Explorer (Solution Explorer), right-click Form1 and select View Designerfrom the shortcut menu (View Designer).
    The designer that contains the Form1 will open.
  2. From the Toolbox, add two buttons to the form.
  3. Reposition these buttons to the right of the form.
  4. Set the properties of the button as shown below. Button Name text button1btnadd Add button button2btnremove Delete button
  5. 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).
  6. In the Form1 class declaration, declare the control array object.
    ' Visual Basic ' declares a new Buttonarray object. Dim Mycontrolarray as buttonarray//c#//declares a new Buttonarray object. Buttonarray Mycontrolarray;
  7. In the form's constructor, add the following code before the end of the method:
    ' Visual Basicmycontrolarray = 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.
  8. In Solution Explorer (Solution Explorer), right-click Form1 and select View Designerfrom the shortcut menu (View Designer).
  9. In the designer, double-click Btnadd to open the code Editor that contains the btnAdd_Click event.
  10. In the btnAdd_Click method, add code to invoke the Mycontrolarray Addnewbutton method:
    ' Visual Basic ' invokes the Mycontrolarray Addnewbutton method. Mycontrolarray.addnewbutton () ' Changes the BackColor property of button 0. Mycontrolarray (0). BackColor = system.drawing.color.red//c#//invokes the Addnewbutton method of the Mycontrolarray. Mycontrolarray.addnewbutton ()//Change the BackColor property of button 0. Mycontrolarray[0]. BackColor = System.Drawing.Color.Red;
  11. In Solution Explorer (Solution Explorer), right-click Form1 and select View Designerfrom the shortcut menu (View Designer).
  12. In the designer, double-click btnremove to open the code Editor that contains the Btnremove_click event.
  13. In the Btnremove_click method, add the following code:
    ' Visual Basic ' calls the Mycontrolarray Remove method. Mycontrolarray.remove ()//c#//invokes the Mycontrolarray Remove method. Mycontrolarray.remove ();
  14. Save the project.

Test Project
    1. From the debug(Debug) menu, select start.
      The Form1opens with three buttons, labeled Addbutton (add),removebutton (delete), and button 1(1).
    2. Click the button 1(Button 1).
      Notice that the screen displays a message box with the index correctly displayed.
    3. 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 button0(buttons 0) has changed to red because of the following line in the btnAdd_Click event:
      Mycontrolarray (0). BackColor = System.Drawing.Color.Red
    4. Click the Remove button (remove buttons) button several times.
      Each click Deletes a button from the form.
    5. Click this button until you delete all the buttons on the left side of the form.
    6. Click the Addbutton again.
      The button is added to the form again and is numbered with the correct index.
Summary
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.

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.