[Transfer] VB.NET and C # .NET CET

xiaoxiao2021-03-06  48

The main use of the array of controls:

l Access a set of controls with the index with the index, allowing the number to retrieve and set data items and repeated over the entire array. This feature can be implemented using the following code.

'Visual Basic Pseudo-Code MyControl (MyIndex) .myproperty = MyValueMyControl (MyIndex 1) .mymethod

// c # pseudo code mycontrol [myindex] .myproperty = myValue; mycontrol [myIndex 1] .mymethod

l Multiple objects use the same event handler (Event Handler) to process events, retrieved and use indexes in these events, the code is as follows:

'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);

l Dynamically add or delete controls during runtime, the code is as follows:

'Visual Basic Pseudo Code DIM I AS IntegerFor I = 1 To 5' Insert Code Create Controls and assign NEXT I for attributes

// c # pseudo code for (int i = 1; i <6; i ) {// insert code to establish controls and assign values ​​to attribute}

Visual Basic .NET and C # allow you to copy some of the features associated with the control array. For example, you can use the commission to bind the events of multiple objects to an event handler. However, if these functions are merged into a dynamic, it is easier to manage. This article will establish components with the following characteristics:

· Establish a collection of indexes and sort controls. The button collection will be used.

· An event handler to handle click event derived button.

· Use the index reference control and the code of the member.

• Dynamically add and delete the code for the control.

Preparatory knowledge

· Understand the properties components and their work.

· Learn more about some components

· Know the syntax of Visual Basic .NET or C # .NET.

create project

The project will be established and named in this section and add a class to the project. This class will encapsulate the code of the array of controls.

1. Select the file-> new-> Project menu Open the New Project dialog.

2. Select the Windows Application project template from the Visual Basic or Visual C # item list, enter ButtonArrayProject in the Name box.

3, select File-> Save All to save the project.

Implement a collection

The ButtonArray class handles transactions that save and organize controls by an implementation of a collection. A collection is an object containing the index object variable list, and also includes methods and other methods such as add, remove. A class that is inherited from System.Collections.CollectionBase (a .NET Framework component), and implementation of the necessary functionality.

Establish the process of inheritance:

1. Select Add Class from the Project menu.

2. Name the class to ButtonArray.vb or ButtonArray.cs depending on the situation. The class code editor will open.

3. In the statement of the class, specify it inherited the System.Collections.collectionBase class from the .NET framework component. 'Visual BasicPublic Class ButtonArrayinherits System.Collections.CollectionBasend Class

// c # public class buttonArray: system.collections.collectionBase {// omitted the code}

The System.Collections.CollectionBase class provides a lot necessary for collection. This includes a list of List objects in the collection, and the count property of the current object in the maintenance collection, allowing the REMOVEAT method of the object to be deleted. They are used when implementing the set of control arrays.

Because each control array is associated with a form, the index must add a field to save the form of the form. By establishing a private, read-only fields to save the reference, you can guarantee that each control array component is only associated with a form.

Establish private, read-only fields for components

Add the following code to the class declaration:

'Visual BasicPrivate Readonly Hostform As System.Windows.Forms.form

// C # private readonly system.windows.forms.form Hostform;

The first method implemented in the collection is AddNewButton. This method creates a new button control and adds it to the target form. You can also use this method to set the initial attribute as the new button.

Implement addNewButton method

Enter the following code in the code editor of the ButtonArray class:

Public function addnewbutton () as system.windows.Forms.Button 'creates a new instance DIM Abutton as new system.windows.Forms.Button () to the Button class Add the button to the collection of internal list me.List.Add ( Abutton 'Add the button in the control collection to the form hostform.controls.add (abutton) that is referenced by the HostForm field, set the initial property Abutton.top = Count * 25abutton.top = count * 25abutton.top = count * 25abutton.TAG = ME. Countabutton.text = "Button" & me.count.tostringreturn Abuttone Dunction

// c # public system.windows.Forms.Button addNewButton () {// creates a new instance system.windows.Forms.Button Abutton = new system.Windows.Forms.Button (); // add this button to the Button class. Go to the internal list this.list.add (abutton); // add the button in the control collection to the form hostform.controls.add (Abutton) referenced by the HostForm field; // Set the initial attribute of the button object Abutton .Top = count * 25; Abutton.Tag = 100; Abutton.tag = this.count; Abutton.Text = "Button" this.count.tostring (); return abutton;}

The function of the above method is:

1. Create a new button.

2. Add it to the control collection of the internal list and the HostForm referenced.

3, set the initial attribute, including setting the tag property to index the button. You can add code to this paragraph to set more properties for the control.

4. Return the new button so that it can be immediately modified and specified to other object references. You must establish a constructor (method running when component is initialized), when a new instance of the array class is established, it is used to set the value of the HostForm field and add the new button to the form. This goal can be used in the following manner.

Establish constructor

Establish constructor for class.

'Visual BasicPublic Sub New (Byval Host As System.Windows.Forms.form) Hostform = hostme.addnewbutton () end sub

// C # // Use the following constructor instead of the default constructor public buttonarray (system.windows.forms.form Host) {hostform = host; this.addnewbutton ();}

The constructor requires a parameter, namely the form of the button array. It specifies this value to the HostForm field, and then add a new button to the form.

An array of exposed controls

The channels of establishing and tracking arrays now have been established, but they must also be exposed to the developer. This function can be implemented by attribute. We will establish a default property (Visual Basic) or an index (C #) to return its reference based on the index of a specific button. This allows you to program the MyButtonArray (MyIndex) syntax in the typical control array.

Establish default properties

Add the following code to the component:

'Visual BasicDefault Public ReadOnly Property Item (ByVal Index As Integer) As _System.Windows.Forms.ButtonGetReturn 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) this.list [index];}}

Implement REMOVE method

The properties of the button in an array now have been established to establish a mechanism for deleting the buttons from the array. To remove a button from the array, you must remove it from the set internal List object and the form's Controls collection.

Add the following method to the component:

'Visual BasicPublic Sub Remove () Check to make sure that the button can delete if me.count> 0 THEN' The last 'Note The last' Note Use the default property hostform when accessing the array. .Controls.remove (me (me.count -1)) me.list.removeat (me.count -1) end ifend sub

// c # public void remove () {// Check to ensure that the button can delete if (this.count> 0) {'from the array button array of the set of controls from the main form, delete the last' Note in the access array Use the default property hostform.controls.remove (this [this.count -1]); this.list.removeat (this.count -1);}}

Establish a public event handler

The final step is to establish an event handler to process a public event for the control array. In the demo, a method will be established for the click event of the button, then adding the code to associate the event with the event handler.

Establish a public event handler

Add the following method to the component:

'Visual BasicPublic Sub ClickHandler (ByVal sender As Object, ByVal e As _System.EventArgs) MessageBox.Show ( "you have clicked button" & CType (CType (sender, _System.Windows.Forms.Button) .Tag, String)) End Sub // C # Public Void ClickHandler (Object Sender, System.EventArgs E) {System.Windows.Forms.MessageBox.show ("You Have Clicked Button" (System.windows.Forms.Button Sender) .tag. Tostring ());

This method shows a message box indicating which button is clicked by retrieving the index of the TAG attribute stored at the button. The parameters of this method are the same as the processed event, and it is necessary for the event handler. You must also associate this event with the event handler.

Associate this event with the event handler

Add the following code to the AddNewButton method:

'Visual Basicaddhandler Abutton.click, Addressof ClickHandler

// c # Abutton.Click = new system.EventHandler (ClickHandler);

Test the project

Now that the components have been completed, an application is required to test the component.

Establish test application

1. In the Solution Manager, right-click Form1 and select View Designer from the pop-up menu.

The design of Form1 is opened.

2, add two buttons to the form.

3. Adjust the position of these buttons to the right side of the form.

4, set the properties of these buttons:

Button Name Text

Button1 btnadd add button

Button2 Btnremove Remove Button

5. In the Solution Manager, right click on Form1 and select View Code from the pop-up menu.

The FORM1 code editor is opened.

6. In the form of Form1, the following control array objects are declared:

'Visual Basic' Declaration New ButtonArray Object DIM MyControlArray As ButtonArray

// c # // Declare the new ButtonArray object ButtonArray mycontrolarray;

7. In the form of the form, add the following code before the end of the method:

'Visual BasicmyControlarray = New ButtonArray (ME)

// c # myControlarray = New ButtonArray (this);

This statement has established a new ButtonArray object. Its parameters (ME or THIS) point to the form of establishing a new ButtonArray, which will become a form of a button array.

Note: In Visual Basic .NET, the constructor is in the "Windows Form Designer Generated Code" code segment, you need to expand this section to view the constructor.

8. In the Solution Manager, right click on Form1 and select View Designer from the pop-up menu.

9. Double-click BTNADD in the designer to open the code editor for btnadd_click event.

10. Add code to call myControlarray in the method btnadd_click: ADDNEWBUTTON method:

'Visual Basic' call AddNewButton method MyControlArray of MyControlArray.AddNewButton () 'change the BackColor property MyControlArray Button 0 (0) .BackColor = System.Drawing.Color.Red// C # // AddNewButton method MyControlArray.AddNewButton call MyControlArray of () ; // Change the backcolor property of Button 0 MyControlarray [0] .BackColor = system.drawing.color.red;

11. In the Solution Manager, right-click on Form1 and select View Designer from the pop-up menu.

12. Double-click BTNRemove in the designer to open the code editor of the btnremove_click event.

13. Add the following code to the btnremove_click method:

'Visual Basic' Remove Method for MYCONTROLARRAY MYCONTROLARRAY.Remove ()

// c # // Call the Remove method mYControlArray.remove ();

14, save items

Test the project

1. Select START from the Debug menu.

The FORM1 form is opened, with three buttons above, the tags are Add Button, Remove Button, and Button 1.

2, click Button 1.

A message box is displayed, and the message box correctly displays the index.

3, click on the Add Button button several times.

Add a new button to the form each time you click. Click on any new button to cause a message box that correctly displays the button index. Note that the color of Button 0 changes to red, which is the result of the following line in the btnadd_click event:

MyControlarray (0) .BackColor = system.drawing.color.red

4, click on the Remove Button button several times.

Remove a button from the form every time you click.

5. Click the Remove Button button until all the buttons on the right side of the form is deleted.

6. Click the Add Button button again.

The button is added again to the form and the number of the index is correct.

in conclusion

This article demonstrates how to build components of the encapsulation control array function. You can see how to build methods to dynamically add and delete controls to form, how to expose objects through the default attribute or indexer. The above code has implemented all functions, and can extend the array of controls for the component to write a custom code.

转载请注明原文地址:https://www.9cbs.com/read-109975.html

New Post(0)