Thursday, March 12, 2009

Adding/Removing dynamically created controls in .NET/C#

There are times when one needs to create and remove controls ; e.g switching from one tab to other, and showing up relevant settings for the tab.

I have found various examples of adding dynamic controls, but removing dynamically created controls are not there.

Adding dynamic controls is easy ;one can find the needful in the InitializeComponent( ). I am giving a example below :-

public void AddControl( )
{
Button myButton = new Button() ;
myButton.Location = new Location ( 10,20);
myButton.Size = new Size(100,25);
myButton.Name = "testButton";
myButton.Text = "Dynamic Button";
myButton.Click += new EventHandler(myButton_Click);
// If you are adding the button to a
// earlier defined GroupBox control, mygroupBox, you can add it as shown below
mygroupBox.Controls.Add(myButton);
}



Removing the button control looks very easy . The following code is meant to iterate through the control collection and dipose them :-

foreach ( Control ChildControls in myGroupBox.Controls)
{
ChildControls.Dispose( );
}


Normally it does destroy the control; but sometimes the above code does not "destroy" the controls. In situations like this , the following code does the trick.List myControls = new List;

public void AddControl( )
{
Button myButton = new Button() ;
myButton.Location = new Location ( 10,20);
myButton.Size = new Size(100,25);
myButton.Name = "testButton";
myButton.Text = "Dynamic Button";
myButton.Click += new EventHandler(myButton_Click);
mygroupBox.Controls.Add(myButton);
// Add the control name to the list
myControls.Add(myButton);
}


The control removal code also changes a little as below :-

foreach (Control removeControl in myControls)
{
this.Controls.Remove(removeControl);
removeControl.Dispose();}
}

No comments :