Pow4Pow5
Pow4Pow5

Reputation: 501

Delete Button that deletes several controls

I am trying to implement a delete button that deletes several other controls such as textbox and combobox that are related to the button. Right now, I succeeded only by deleting one control by using tag function as follows:

private void deleteControl(object sender, MouseEventArgs e)
{
   Button btn = (Button)sender;

   TextBox txtbox = (TextBox)this.Controls.Find(btn.Tag.ToString(), true)[0];
   txtbox.Dispose();
}

The above code is a code snippet from my function that I implemented. However, I only can delete 1 Control by using this method since I only can tag one Control to my delete button. So how should I implement if I want to delete 2 controls using a delete button?

Upvotes: 3

Views: 227

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29026

Try this; Iterate through available controls and delete Delete according to the condition

foreach (Control ctrl in this.Controls.OfType<Control>().ToList())
{
    if ((ctrl.GetType() == typeof(TextBox) || ctrl.GetType() == typeof(ComboBox))
        && ctrl.Tag.ToString() == btn.Tag.ToString())
    {
        ctrl.Dispose();
    }
}

Upvotes: 2

misha130
misha130

Reputation: 5726

You can simply do

this.Controls.Remove(btn);

Or if you want to remove all

this.Controls.RemoveAll();

Don't forget that controls are in containers so you can also do this to delete all siblings

btn.Parent.Controls.RemoveAll();

Upvotes: -1

Related Questions