I have a problem in my C# winform project.
In my project I have function that make a new button at runtime. Because sometimes I make too many buttons I want to write a function that deletes the button that I want to delete at run time.
Someone maybe have already that function?
private void button2_Click(object sender, EventArgs e)
{
Button myText = new Button();
myText.Tag = counter;
myText.Location = new Point(x2,y2);
myText.Text = Convert.ToString(textBox3.Text);
this.Controls.Add(myText);
}
that is how I make the button at runtime.
you should be able to use this.Controls.Remove(myText);
In order to remove the last button you've added, you can use something like this:
This should allow you to remove as many buttons as you want by removing always the last one added from the existing ones.
Update
If you want to be able to hover a button with your mouse cursor and then delete it with Delete key, you can use this solution:
KeyPreview
to true, soForm
can receive key events occured in its controlsadd
buttonsAdded
list and modifybutton2_Click
as in the first solution described in this answercreate
KeyDown
event handler for yourForm
and add this code ot it:if you want to remove on delete key press you can use key down event as below