Delete selected buttons on Windows Forms C# | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Delete selected buttons on Windows Forms C#

I need to click on a button, "select" that button, and by clicking on an erase button, that control will be deleted. How could I do that ?.

25th May 2018, 4:16 AM
SebGM2018
SebGM2018 - avatar
3 Answers
+ 1
The form has a collection of controls. This collection holds all controls of the form. You can request the form. How many controls there are on the form. And what type they are "this" in the code below is the windows-form that holds the controls. MessageBox.Show(this.Controls.Count.ToString()); foreach (Control AControl in this.Controls) { MessageBox.Show(AControl.Name); MessageBox.Show(AControl.GetType().ToString()); } this.Controls.RemoveByKey("button3"); // parameter is buttonname this.Controls.Remove(button2); //parameter is button object
25th May 2018, 9:06 PM
sneeze
sneeze - avatar
0
i need that when you click a garbage button, the "Selection mode" turn on (A bool variable became true) and when you click that control (let's say a button) the application "selects it" and with another button, (Ok button) the application should knew Wich controls you clicked, and then, delete them, the problem i Have is in the recognize witch controls you selected
25th May 2018, 11:46 PM
SebGM2018
SebGM2018 - avatar
0
A click on a button will always go to the button_click or other connected event. So in that event you need to check if the DeleteMode is true and if so you have to take some action. When the DeleteMode is false you can do want the button does if the DeletionMode is not selected Either you have a list of controls and add the object to that list or you add a special character to the "tag" property. The tag property is a nice label like property which you can set to flag / or recognize objects. Each event a a sender parameter, even if you have connected multiple controls to one event this parameter will always tell you with control was clicked. private void button2_Click(object sender, EventArgs e) { MessageBox.Show(sender.GetType().ToString()); if (sender is Button) { MessageBox.Show(((Button)sender).Name); } if (DeletionMode) { //add button to ControlsToBeDeletedList //or ((Button)sender).Tag = "Delete"; } else { //do the normal button click stuff } }
27th May 2018, 6:58 PM
sneeze
sneeze - avatar