Nidzzz
Nidzzz

Reputation: 1

Delete seleted button generated dynamically

I have developed a winform application in C#. I want to generate buttons dynamically on button click, lets name it "Add". On clicking any button randomly, then clicking delete button, that selected button should be deleted. Now how can I do this?

here is my dynamically button generation code


public void AddNewButton()
{
    System.Windows.Forms.Button();
    Btn = new Button();
    this.Controls.Add(Btn);
    Btn.Name = textBox_code.Text + count;
    Btn.Location = new Point(50, 50);
    Btn.Text = textBox_code.Text;
    Btn.BackColor = Color.Red;
    Btn.ForeColor = Color.Blue;
    Btn.Click += new EventHandler(this.button_Click);
    count = count + 1;
    label1.Text = count.ToString();
    Btn.MouseDown += new MouseEventHandler(textbox_MouseDown);
    Btn.MouseMove += new MouseEventHandler(textbox_MouseMove);
    Btn.MouseUp += new MouseEventHandler(textbox_MouseUp);
}

and for deleting the button

private void button_delete_Click(object sender, EventArgs e)
{
    this.Controls.Remove(Btn);
    count = count - 1;
    label1.Text = count.ToString();
}

This above code deletes only last added button not any random selected button

Upvotes: 0

Views: 67

Answers (2)

Pikoh
Pikoh

Reputation: 7703

You don't explain how you select the button to be deleted, but as a general answer using the name of the button, instead of

this.Controls.Remove(Btn);

What about

foreach (Control c in this.Controls)
{
     if (c.Name == "Name of button to delete")
     {
           this.Controls.Remove(c);
           break;
     }
}

EDIT

Ok, you do explain the process. Then a way to do it is to have a variable to store the last clicked button:

Button btnLastClicked;

Then in the button_Click event handler, do this:

btnLastClicked=sender as Button;

Finally,

private void button_delete_Click(object sender, EventArgs e)
{
    this.Controls.Remove(btnLastClicked);
    count = count - 1;
    label1.Text = count.ToString();
}

Upvotes: 0

mike
mike

Reputation: 475

Add a variable to hold the last clicked button (at the class level)

Button lastClicked = null;
private void button_Click(object sender, EventArgs args) 
{
    ...
}

In your button_Click add this,

private void button_Click(object sender, EventArgs args) 
{
    // whatever you already have...

    lastClicked = (Button)sender;
}

And then in your delete button handler,

private void button_delete_Click(object sender, EventArgs e)
{
    // delete the last clicked button
    this.Controls.Remove(lastClicked);
    count = count - 1;
    label1.Text = count.ToString();
}

Upvotes: 2

Related Questions