Search code examples
c#buttonarraylistpanel

Add/remove buttons to a panel with an arraylist c#


So what I want is to add strings to my arraylist and then show it in a panel as buttons and if you click on then it removes it from the array and the panel.

So what I have is

Add button:

if (!tags.Contains(tag.Text) ) {
    tags.Add(tag.Text);
    organizeTags(tags);
}
else {
    MessageBox.Show("Ese tag ya está registrado", "Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
label10.Text = tags.Count.ToString();

The remove button:

private void Button_Click(object sender, EventArgs e)
{
    Button button = new Button();
    button = (Button)sender;
    tags.Remove(button.Name);
    organizeTags(tags);
}

And the organizeTags function:

private void organizaTags(ArrayList tags)
{
    panel1.Controls.Clear();
    ArrayList botones = new ArrayList();
    int j = 0, i = 0;
    foreach (string element in tags) {
        Button button = new Button();
        button.Name = textBox6.Text;
        button.Text = textBox6.Text;
        button.Width = 100;
        button.Left = i * 100;
        button.Top = j * 30;
        button.Click += new EventHandler(Button_Click);
        panel1.Controls.Add(button);
        i++;
        if (i == 6)
        {
            j++;
            i = 0;
        }            
    }
}

But it works horribly, it creates 2 buttons with the same name, then it only deletes the first button and I don't know how to fix it.


Solution

  • Change:

        button.Name = textBox6.Text;
        button.Text = textBox6.Text;
    

    To:

        button.Name = element;
        button.Text = element;