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
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 :
Post a Comment