I have dynamically generated controls on the panels of windows form and i have also generated a button for removing the controls, all in rows.
int c = 0;
private void button1_Click(object sender, EventArgs e)
{
int v;
v = c++;
panel1.VerticalScroll.Value = VerticalScroll.Minimum;
ComboBox combo = new ComboBox();
combo.Name = "combobox" + v ;
combo.Location = new Point(30, 5 + (30 * v));
ComboBox combo2 = new ComboBox();
combo2.Name = "combobox2" + v ;
combo2.Location = new Point(170, 5 + (30 * v));
TextBox txt = new TextBox();
txt.Name = "txtbx" + v;
txt.Location = new Point(300, 5 + (30 * v));
TextBox txt2 = new TextBox();
txt2.Name = "txtbx2" + v;
txt2.Location = new Point(450, 5 + (30 * v));
TextBox txt3 = new TextBox();
txt3.Name = "txtbx3" + v;
txt3.Location = new Point(600, 5 + (30 * v));
Button btn = new Button();
btn.Name = "btn" + v;
btn.Text = "Remove";
btn.Location = new Point(750, 5 + (30 * v));
panel1.Controls.Add(combo);
panel1.Controls.Add(btn);
panel1.Controls.Add(txt);
panel1.Controls.Add(combo2);
panel1.Controls.Add(txt2);
panel1.Controls.Add(txt3);
btn.Click += new EventHandler(btn_Click);
combo.Tag = btn;
combo2.Tag = combo;
btn.Tag = combo2;
}
private void btn_Click(object sender, EventArgs e)
{
ComboBox cb3 = btnh.Tag as ComboBox;
ComboBox cb4 = cb3.Tag as ComboBox;
panel1.Controls.Remove(cb3);
panel1.Controls.Remove(cb4);
panel1.Controls.Remove(btnh);
}
Now how do I remove all the controls from a row upon clicking a button from that row?
If all of your controls that you want to delete are in a Panel, you can do:
panel.Controls.Clear();
That clears all controls form your panel.Remove control events. From MSDN:
Specific examples are given using VB and C# in the linked page.
If you have a Panel o other container with more dinamicaly components for remove all or more than one you can proceed in this way.
In first step you load a component in array or list.
You are still not saying which control you want to remove, what type of controls you want to remove or how you want to identify them.
You could just loop through the controls to remove specific Controls.
If you have
Linq
, its easy:Edit:
Its easy to do the same since you're tagging the control already. All you need is to just retrieve the control back from tag. But you need to tag appropriately:
Do this instead:
Here you are tagging controls with the button, hence on the button click you can remove all the controls whose tags are the clicked button which you get from
sender
argument. But the downside of this approach is that you have to enumerate all the controls of the panel which is not great.Edit: As I came to learn the below code is for a table layout panel which the OP isn't using for now. But anyway a table panel layout is better suited for this job.
I would suggest you to do this: