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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With