2

I'm making a program that will make buttons on the screen from a for loop. This is important because the user needs to have access to the number of buttons, and could change with every run. This is the code i have so far:

public Form1()
    {
        InitializeComponent();
        int top = 5;
        int left = 5;
        for (int i = 0; i < 10; i++)
        {
            Button button = new Button();
            button.Height = 50;
            button.Left = left;
            button.Top = top;
            this.Controls.Add(button);
            left += button.Width + 2;
        }
    }

What i want is basically something like this:

Button b+i = new Button();

Its like when combining two strings, i want the name of the button on the first run in the loop to be b0, then b1, then b2, and so on.

I use Visual Studio, and InitializeComponent() goes to the editor generated code to make the window and stuff. nothing but the window is made there.

Thank you for your help!

7
  • 1
    You can use button.Name to set a name like string.Format("button{0}", i), also you can put i in tag and use it when you need. Commented Jan 8, 2016 at 1:20
  • 5
    You're not asking about setting the button's name. You're asking about changing the name of the variable that is holding the button instance, and you can't do that at runtime. Use an array to contain the buttons, and then you can reference them by index. Commented Jan 8, 2016 at 1:23
  • You may find this Q/A helpful: Dynamic button creation & placing them in a predefined order using c# Commented Jan 8, 2016 at 1:27
  • Is the question answered in comments? Commented Jan 8, 2016 at 1:38
  • @RezaAghaei yes, using what was given by you, KenWhite, and MitchWheat i was able to figure it out. the following link will also summarize things with the concepts provided by you guys. link for future people with the same concern Commented Jan 8, 2016 at 1:41

2 Answers 2

5

Worrying about the variable names is the wrong way to approach this problem. There are several alternatives:

Use a list

List<Button> buttons;    

public Form1()
{
    InitializeComponent();
    buttons = new List<Button>();
    int top = 5;
    int left = 5;
    for (int i = 0; i < 10; i++)
    {
        Button button = new Button();
        button.Height = 50;
        button.Left = left;
        button.Top = top;
        this.Controls.Add(button);
        buttons.Add(button);
        left += button.Width + 2;
    }
}
//now instead of 'b1', it's 'buttons[1]'

Which you could also create with the OfType() method:

var buttons = this.Controls.OfType<Button>().ToList();

These can be done in combination with a FlowLayoutPanel or TableLayoutPanel to simplify the code:

public Form1()
{
    InitializeComponent();

    for (int i = 0; i < 10; i++)
    {
        Button button = new Button();
        button.Height = 50;
        FlowLayoutPanel1.Controls.Add(button); //panel handles Left/Top location
    }
}

The panel also has the advantage of helping your app scale at different dpi's or screen/window sizes.

Any of which could also be adapted to start thinking in terms of connecting to a datasource (and reduce the code):

var buttons = Enumerable.Range(0, 10).Select(b => new Button {
   Height = 50,
   Left = 5 + ( b * (BUTTONWIDTH + 2) ),
   Top = 5,
   Name = String.Format("Button{0}", b)
});

//buttons.ToList()
//or
//this.Controls.AddRange(buttons.ToArray())
//or 
//FlowLayoutPanel1.Controls.AddRange(buttons.ToArray()) //Remove Left/Top code

But all of this is meaningless until you can get the buttons to actually do something. You need an event handler for (at least) the Click event:

foreach (var b in butons)
{
     b.Click += (s,e) => 
    { 
        //click code for all of the buttons goes here
        // you can tell the buttons apart by looking at the "s" variable 

    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

Both are legal. Scroll down on the docs page for object and list initializers and you'll see the example.
Oops, thought it was only legal when you used a parametized constructor. Thanks for the clarification
if i could "vote" for this answer a thousand times i would. This is so amazing. You're so amazing. thank you sir.
1

since people (rightly) said 'use an array' here is code

public Form1()
    {
        InitializeComponent();
        int top = 5;
        int left = 5;
        var buttons = new Button[10];
        for (int i = 0; i < 10; i++)
        {
            Button button = new Button();
            button.Height = 50;
            button.Left = left;
            button.Top = top;
            this.Controls.Add(button);
            left += button.Width + 2;
            buttons[i] = button;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.