Create a control array in Visual Basic. NET and Visual C #. net

Source: Internet
Author: User



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

    1. InFile(File) menu, pointingNew(New), and then selectProject(Project) to openNew project(New project) dialog box.
    2. Select from the Visual Basic or Visual C # project listWindows Application(Windows Application) Project template, and inNameIn the (name) box, typeButtonarrayproject.
    3. SlaveFile(File) menu, selectSave all(Save all) to save the project.
Implementation set

ButtonarrayClass 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

    1. SlaveProject(Project), selectAdd class(Add a class ).
    2. Name the classButtonarray. VBOrButtonarray. CS.

      The Code Editor containing the class will be opened ).

    3. 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

    • Add the following code directly in the class declaration:
      'Visual basic
      Private readonly hostform as system. Windows. Forms. Form

      // C #
      Private readonly system. Windows. Forms. Form hostform;

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

  • In the code editor that contains the buttonarray class, type the following code:
     Public sub addnewbutton () 
    'create a new instance of the button class.
    dim abutton as new system. Windows. Forms. Button ()
    'Add the button to the internal list of the set.
    me. List. Add (abutton)
    'Add the button to the control set of the form referenced by the hostform field
    .
    hostform. Controls. Add (abutton)
    'sets the initial attribute of the button object.
    abutton. top = count * 25
    abutton. left = 100
    abutton. tag = me. count
    abutton. TEXT = "button" & me. count. tostring
    end sub
    /C #
    Public void addnewbutton ()
    {< br> // 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 control set of the form referenced by the hostform field
    .
    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:

    1. Create button.
    2. Add the new button to the internal list andHostformControl Set of the referenced form.
    3. 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 settingHostformField 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 specifiesHostformAnd then callAddnewbuttonMethod 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

    • Add the following methods to the component.
      'Visual basic
      Public sub remove ()
      'Check to make sure there are buttons to be deleted.
      If me. Count> 0 then
      'Delete the added to array from the host Form Control Set
      . Note that when accessing the Array
      'Use of default properties.
      Hostform. Controls. Remove (Me. Count-1 ))
      Me. List. removeat (Me. Count-1)
      End if
      End sub

      // 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.
      '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

    • InAddnewbuttonMethod To Add the following code.
      '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

  1. In Solution Explorer, right-clickForm1And selectView designer(View designer ).

    Will open the includeForm1.

  2. From the toolbox, add the two buttons to the form.
  3. Place the buttons on the right of the form.
  4. Set the button properties as follows.
    Button Name Text
    Button1 Btnadd Add button
    Button2 Btnremove Delete button
  5. In Solution Explorer, right-clickForm1And selectView code(View the Code ).

    The Code Editor containing form1 will be opened ).

  6. 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;
  7. 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 newButtonarrayObject. Parameters (MeOrThis) Will reference to create a newButtonarrayAnd will become the form for placing the button array.

  8. In Solution Explorer, right-clickForm1And selectView designer(View designer ).
  9. In the designer, double-clickBtnaddTo openBtnadd_clickEvent code editor ).
  10. InBtnadd_clickMethod, add code to callMycontrolarrayOfAddnewbuttonMethod:
    '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;
  11. In Solution Explorer, right-clickForm1And selectView designer(View designer ).
  12. In the designer, double-clickBtnremoveTo openBtnremove_clickEvent code editor ).
  13. 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 ();
  14. Save the project.

Test Item

    1. SlaveDebugIn the (Debug) menu, selectStart(START ).

      Will openForm1Contains three buttons markedAdd button(Add button ),Remove button(Delete button) andButton 1(Button 1 ).

    2. ClickButton 1(Button 1 ).

      Note: a message box is displayed, with the index correctly displayed.

    3. 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
    4. Click several timesRemove button(Delete button) button.

      Each click will delete a button from the form.

    5. Click this button until all the buttons on the left of the form are deleted.
    6. 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.

Related Article

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.