Vereonix
Vereonix

Reputation: 1414

How to remove buttons that were procedurally generated

I generate a number of buttons within my winform based on what is in a list this works fine, however I need to reset the form back to having none of the new buttons existing.

The button generating code is:

private int importButtonFactory()
        {
            int numberOfButtons = 0;

            int top = 70;
            int left = 12;

            foreach (Import import in ImportList)
            {
                Button importButton = new Button();
                importButton.Left = left;
                importButton.Top = top;
                importButton.Width = 220;
                this.Controls.Add(importButton);
                top += importButton.Height + 2;
                numberOfButtons++;
                importButton.Text = import.Mapping;
                importButton.Click += (object sndr, EventArgs c_args) => openFile_Click(import.Path);
            }

            return numberOfButtons;
        }

I have tried following within a separate function:

Controls.Remove(importButton);

But I get the error: "The name 'importButton' does not exist in the current context"

Upvotes: 0

Views: 333

Answers (1)

Rahul
Rahul

Reputation: 77896

Yes and that's cause the control instance declared inside a different function. You can create a List<Button> and have them clear later like

List<Button> buttonList = new List<Button>();



private int importButtonFactory()
        {
            int numberOfButtons = 0;

            foreach (Import import in ImportList)
            {
                Button importButton = new Button();
                ....


               buttonList.Add(importButton);
         }

In your other method you can access the list and remove them

Upvotes: 1

Related Questions