C # dynamically add and delete controls in. net

Source: Internet
Author: User

C # dynamically add and delete controls in. net
 
Introduction

Arrays provide a convenient way for a group of controls that share common functions to work together. For example, a group of controls may be used to display related data or provide related behaviors when clicked. C # itself does not support the creation of control arrays, but you can copy all functions of the control array through programming. This article describes how to create a simple component for the copy control array function.

The main functions of the control array are:

1. Access a group of controls with the same name and index. You can use numbers to retrieve and set data items and repeat them in the entire array. This function can use the followingCode.

Pseudocode
Mycontrol [myindex]. myproperty = myvalue;
Mycontrol [myindex + 1]. mymethod
 
2. Multiple objects are processed using the same eventProgramEvent Handler is used to process events and query and use indexes in these events. The Code is as follows:

Pseudocode
Private void mycontrol_click (system. Object sender, system. eventargs E)
{
MessageBox. Show ("You have clicked mycontrol number" +
Mycontrol. Index );
}

3. add or delete controls dynamically at runtime. The Code is as follows:

Pseudocode
For (INT I = 1; I <6; I ++)
{
// Insert code to create controls and assign values to attributes
}
 
C # allows you to copy some functions related to the control array. For example, you can use a delegate to bind events of multiple objects to an event handler. However, it is easier to integrate these functions into a dynamic and easy-to-manage component. This article will create components with the following features:

· Create a set of indexes and sorting controls. The button set is used for demonstration.

· An event handler is used to process the click events of derivative buttons.

· Code for referencing controls and members using indexes.

· Dynamically add and delete controls to and from a form.

 

Create a project

In this section, a project is created and named, and a class is added to the project. This class encapsulates the code that implements the control array.

1. Select File> New> project to open the new project dialog box.

2. Select the Windows Application Project template from the Visual C # project list and enter the buttonarrayproject In the Name box.

3. Select File> Save all to save the project.

Implement a set

The buttonarray class processes transactions that store and organize control arrays through the implementation of a set. A set is an object that contains the list of index object variables. It also contains methods such as add and remove and other operation objects. This section describes how to create a class that inherits from system. Collections. collectionbase (the class that provides the necessary collection functions in the. NET Framework component) and provide necessary functions.

The process of creating an inherited class:

1. Select Add class from the project menu.

2. Name the class buttonarray. CS as needed. Class editor will open.

3. In the class declaration, specify that it inherits from the system. Collections. collectionbase class of the. NET Framework component.

Public class buttonarray: system. Collections. collectionbase
{
// The code added by the designer is omitted.
}
 
The system. Collections. collectionbase class provides many necessary functions for collections. This includes a list object of objects in a tracking set. It maintains the Count attribute of the current number of objects in the set and allows you to delete the removeat method of objects indexed at a specific position. These are used when implementing the control array set.

Because each control array is associated with a form, an index must add a field to save the reference of the form. By creating private and read-only fields to save the reference, each control array component can be associated with only one form.

Create private and read-only fields for components

Add the following code to the class declaration immediately:

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 initial attributes for the new button.

Addnewbutton Method

Enter the following code in the code editor of The buttonarray class:

Public System. Windows. Forms. Button addnewbutton ()
{
// Create a new instance for 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 buttons in the control set to 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 ();
Return abutton;
}
 

The functions of the above method are as follows:

1. Create a New button.

2. Add it to the internal list and the control set of the form referenced by hostform.

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

4. Return the new button so that it can be immediately modified and specified to reference other objects.

You must create a constructor (the method that runs when the component is initialized). When a new instance of the control array class is created, it is used to set the value of the hostform field and add the new button to the form. You can use the following methods to achieve this goal.

Create Constructor

Create a constructor for the class.

// Use the following 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 specifies the value to the hostform field, and adds a new button to the form using the addnewbutton method of the class.

Exposure Control Array

Now you have created a way to create and track controls in an array, but you must expose them to developers. This function can be implemented through attributes. We will create a default indexer to return its reference based on the index of a specific button. In this way, you can program the mybuttonarray (myindex) syntax in the typical control array.

Create default properties

Add the following code to the component:

Public System. Windows. Forms. Button this [int Index]
{
Get
{
Return (system. Windows. Forms. Button) This. list [Index];
}
}
 

Remove Method

Now the attribute of the button in the exposure array has been set up, and you can create a mechanism to delete the button from the array. To delete a button from an array, you must delete it from the internal list object of the Set and the controls set of the form.

Add the following method to the component:

Public void remove ()
{
// Check to ensure a button can be deleted
If (this. Count> 0)
{
'Delete the last one from the array button array of the control set on the main form.
'Note that the default attribute is used when accessing the array.
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 for the control array to process common events. In the demo, a method is created for the button click event, and the code is added to associate the event with the event handler.

Create a public event handler

Add the following method to the component:

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 retrieves the index of the tag attribute stored in the button and displays a message box indicating which button was clicked. The parameters of this method are the same as those of the event to be processed. It is necessary for the event handler. You must also associate the event with the event handler.

Associate the event with the event handler

Add the following code to the addnewbutton method:

Abutton. Click + = new system. eventhandler (clickhandler );
 

Test this project

Now that the component is complete, you need to create an application to test the component.

Create a test application

1. In solution manager, right-click form1 and select View designer from the pop-up menu.

The form1 designer is turned on.

2. Add two buttons to the form.

3. Adjust the buttons to the right of the form.

4. Set the attributes of these buttons:

Button Name text

Button1 btnadd Add button

Button2 btnremove Remove button

5. In solution manager, right-click form1 and select view code from the pop-up menu.

The code editor of form1 is opened.

6. In the form1 class declaration, declare the following control array object:

// Declare a new buttonarray object
Buttonarray mycontrolarray;
 

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

Mycontrolarray = new buttonarray (this );
 

This statement creates a new buttonarray object. Its Parameter this points to the new buttonarray form, which will become the form for placing the button array.

8. In solution manager, right-click form1 and select View designer from the pop-up menu.

9. Double-click btnadd In the designer to open the code editor for the btnadd_click event.

10. Add code in method btnadd_click to call the addnewbutton method of mycontrolarray:

// Call the addnewbutton method of mycontrolarray
Mycontrolarray. addnewbutton ();
// Change the backcolor attribute of Button 0
Mycontrolarray [0]. backcolor = system. Drawing. color. Red;
 

11. In solution manager, right-click form1 and select View designer from the pop-up menu.

12. Double-click btnremove In the designer to open the code editor for the btnremove_click event.

13. Add the following code to the btnremove_click method:

// Call the Remove Method of mycontrolarray
Mycontrolarray. Remove ();
 

14. Save the project

Test the project www.w3sky.com.

1. Select Start from the Debug menu.

The form1 form is opened with three buttons on it. The labels 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 the Add button several times.

Each click adds a new button to the form. Clicking any new button will result in a message box that correctly displays the index of this button. Note that the color of Button 0 is changed to red, which is the result of the following line in the btnadd_click event:

Mycontrolarray (0). backcolor = system. Drawing. color. Red

4. Click the Remove button several times.

Delete a button from the form each time you click it.

5. Click the Remove button until all the buttons on the right of the form are deleted.

6. Click Add button again.

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

Conclusion

This article demonstrates how to create components that encapsulate the control array function. You can see how to createCubeTo dynamically add and delete controls to and from the form, and how to expose objects through the default attribute or indexer. The above code has implemented all functions, and you can also extend the control array by writing custom code for the component.
 

Code:
Form1.cs

 

Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;

Namespace daddcontrol
{
/// <Summary>
/// Summary of form1.
/// </Summary>
Public class form1: system. Windows. Forms. Form
{
Private system. Windows. Forms. Button btnadd;
Private system. Windows. Forms. Button btnremove;
Buttonarray mycontrolarray;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;

Public form1 ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();

//
// Todo: add Any constructor code after initializecomponent calls
//
Mycontrolarray = new buttonarray (this );
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. btnadd = new system. Windows. Forms. Button ();
This. btnremove = new system. Windows. Forms. Button ();
This. suspendlayout ();
//
// Btnadd
//
This. btnadd. Location = new system. Drawing. Point (216, 0 );
This. btnadd. Name = "btnadd ";
This. btnadd. tabindex = 0;
This. btnadd. Text = "Add button ";
This. btnadd. Click + = new system. eventhandler (this. btnadd_click );
//
// Btnremove
//
This. btnremove. Location = new system. Drawing. Point (216,240 );
This. btnremove. Name = "btnremove ";
This. btnremove. tabindex = 1;
This. btnremove. Text = "Remove button ";
This. btnremove. Click + = new system. eventhandler (this. btnremove_click );
//
// Form1
//
This. autoscalebasesize = new system. Drawing. Size (6, 14 );
This. clientsize = new system. Drawing. Size (292,266 );
This. Controls. Add (this. btnremove );
This. Controls. Add (this. btnadd );
This. Name = "form1 ";
This. Text = "form1 ";
This. resumelayout (false );

}
# Endregion

/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (New form1 ());
}

Private void btnadd_click (Object sender, system. eventargs E)
{
// From www.w3sky.com
// Call the addnewbutton method of mycontrolarray
Mycontrolarray. addnewbutton ();
// Change the backcolor attribute of Button 0
Mycontrolarray [0]. backcolor = system. Drawing. color. Red;
}

Private void btnremove_click (Object sender, system. eventargs E)
{
Mycontrolarray. Remove ();
}
}
}

 

 

Buttonarray. CS

 

Using system;
Using system. Windows. forms;

Namespace daddcontrol
{
/// <Summary>
/// Summary of buttonarray.
/// </Summary>
Public class buttonarray
: System. Collections. collectionbase
{
Private readonly system. Windows. Forms. Form hostform;

Public buttonarray ()
{
//
// Todo: add the constructor logic here
//
}

Public buttonarray (system. Windows. Forms. form host)
{
Hostform = host;
// This. addnewbutton ();
}

public system. windows. forms. button addnewbutton ()
{< br> // creates a new instance for 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 buttons in the control set to 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 ();
abutton. click + = new system. eventhandler (clickhandler);
return abutton;
}

Public System. Windows. Forms. Button this [int Index]
{
Get
{
Return (system. Windows. Forms. Button) This. list [Index];
}
}

Public void remove ()
{
// Check to ensure a button can be deleted
If (this. Count> 0)
{
// From www.w3sky.com
// Delete the last one from the array button array of the control set on the main form
// Note that the default attribute is used when accessing the array.
Hostform. Controls. Remove (this [This. Count-1]);
This. List. removeat (this. Count-1 );
}
}


Public void clickhandler (Object sender, system. eventargs E)
{
System. Windows. Forms. MessageBox. Show ("You have clicked button" +
(System. Windows. Forms. Button) sender). Tag. tostring ());
}
}
}

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.