简体   繁体   中英

Dynamically create buttons in c# by user at runtime

How to create buttons dynamically after user input in C# (Visual Studio). There is a text-box to enter how many buttons user wants? Then my target is to create buttons below the input field as the user wants then how can I get id's of that buttons?

private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(buttons[i]);
    }
}

Here I first added an event handler to the textbox , which is called whenever the text value is changed. The value is converted to the int value and then is used in a for loop statement. You can set your button's potion to the desired value using location property. Using tag or name property you can assign a unique value to your buttons. I hope the code helps.

Look at the code below :

private void Form1_Load(object sender, EventArgs e)
{
 textBox1.TextChanged += textBox1_TextChanged;
}

void textBox1_TextChanged(object sender, EventArgs e)
{
 var txtBox = sender as TextBox;
 if (txtBox == null) return;
 var count = Convert.ToInt16(txtBox.Text);
 //
 var xPosition = 0;
 for (var i = 1; i <= count; i++)
 {
  var button = new Button
  {
   Tag = string.Format("Btn{0}", i),
   Text = string.Format("Button{0}",i),                        
   Location = new Point(xPosition, 0)
  };
 xPosition = xPosition + 100;
 Controls.Add(button);
}

When you are creating Control(in your case Buttons) you can give them Name property. It will be very good if that name will be unique.

var btn = new Button();
btn.Name = "MyBtn";
btn.Text = "Our Button";
this.Controls.Add(btn);

For creation of N buttons you just need to put this in a Loop with N iterations and set btn.Name to something like "Name"+SomeNumber. To set the Position of the Buttons to below the input you should set btn.Left and btn.Top to the corresponding coordinates.

Then when you need to work with generated Control/Button you can do search by that Name in the following way:

var btn = (Button)this.Controls.Find("MyBtn", true).First();

and do whatever you want with that Control/Button.

But in this case there is some danger as I am not checking if there was found any control with that name. If you write incorrect Name this will throw exception on .First() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM