Jared
Jared

Reputation: 4810

Populate form with controls based on int value

I was wondering how to go about doing something such as this:

I need to create a Form with a specific number of buttons based on an integer value representing the number of buttons needed, then give them their own specific names so that each can have their own unique event handlers.

A real example I can think of doing this would be the Windows log-in screen, where the number of controls created is based on the number of users and whether there is a Guest account or not. How do you think that they programmed that?

Thank you.

Upvotes: 1

Views: 101

Answers (2)

Mitja Bonca
Mitja Bonca

Reputation: 4546

Somehow you have to define the names of all the buttons. I would suggest you to create a new string array and write the button names inside, and then use them in buttons creation loop:

//do the same length as the for loop below:
string[] buttonNames = { "button1", "button2", "button3", "button4", "button5" };

for (int i = 0; i < buttonNames.Lenght; i++)
{
  Button newButton = new Button();
  newButton.Name = "button" + i.ToString();
  newButton.Text = buttonNames[i]; //each button will now get its own name from array
  newButton.Location = new Point(32, i * 32);
  newbutton.Size = new Size(25,100); //maybe you can set different sizes too (especially for X axes)
  newButton.Click += new EventHandler(buttons_Click);
  this.Controls.Add(newButton);
}


private void buttons_Click(object sender, EventArgs e)
{
  Button btn = sender as Button
  MessageBox.Show("You clicked button: " + btn.Text + ".");
}

Upvotes: 0

LarsTech
LarsTech

Reputation: 81620

for (int i = 0; i < 5; i++)
{
  Button newButton = new Button();
  newButton.Name = "button" + i.ToString();
  newButton.Text = "Button #" + i.ToString();
  newButton.Location = new Point(32, i * 32);
  newButton.Click += new EventHandler(button1_Click);
  this.Controls.Add(newButton);
}

private void button1_Click(object sender, EventArgs e)
{
  if (((Button)sender).Name == "button0")
    MessageBox.Show("Button 0");
  else if (((Button)sender).Name == "button1")
    MessageBox.Show("Button 1");
}

Upvotes: 1

Related Questions