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.
In order to remove the last button you've added, you can use something like this:
//a list where you save all the buttons created
List<Button> buttonsAdded = new List<Button>();
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);
//add reference of the button to the list
buttonsAdded.Insert(0, myText);
}
//atach this to a button removing the other buttons
private void removingButton_Click(object sender, EventArgs e)
{
if (buttonsAdded.Count > 0)
{
Button buttonToRemove = buttonsAdded[0];
buttonsAdded.Remove(buttonToRemove);
this.Controls.Remove(buttonToRemove);
}
}
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:
- set
KeyPreview
to true, so Form
can receive key events occured in its controls
add buttonsAdded
list and modify button2_Click
as in the first solution described in this answer
create KeyDown
event handler for your Form
and add this code ot it:
private void MySampleForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
//get control hovered with mouse
Button buttonToRemove = (this.GetChildAtPoint(this.PointToClient(Cursor.Position)) as Button);
//if it's a Button, remove it from the form
if (buttonsAdded.Contains(buttonToRemove))
{
buttonsAdded.Remove(buttonToRemove);
this.Controls.Remove(buttonToRemove);
}
}
}
you should be able to use this.Controls.Remove(myText);
public Button myText ; // keep public button to assign your new Button
private void buttonAdd_Click(object sender, EventArgs e)
{
myText = new Button();
myText.Tag = counter;
myText.Location = new Point(x2,y2);
myText.Text = Convert.ToString(textBox3.Text);
this.Controls.Add(myText);
}
private void buttonRemove_Click(object sender, EventArgs e)
{
if(Button != null && this.Controls.Contains(myText))
{
this.Controls.Remove(myText);
myText.Dispose();
)
}
if you want to remove on delete key press you can use key down event as below
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
if(Button != null && this.Controls.Contains(myText))
{
this.Controls.Remove(myText);
myText.Dispose();
)
}
}