[英]Dynamically create buttons in c# by user at runtime
How to create buttons dynamically after user input in C# (Visual Studio). 用户在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?
然后,我的目标是根据用户的需要在输入字段下方创建按钮,然后如何获取该按钮的ID?
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. 在这里,我首先向
textbox
添加了一个事件处理程序,每当更改文本值时都会调用该事件处理程序。 The value is converted to the int
value and then is used in a for loop statement. 该值将转换为
int
值,然后在for循环语句中使用。 You can set your button's potion to the desired value using location property. 您可以使用location属性将按钮的药水设置为所需的值。 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. 创建控件(在您的情况下为Button)时,可以给它们提供
Name
属性。 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. 为了创建N个
buttons
您只需要将其放入N个迭代的循环中,并将btn.Name
设置为“ 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. 要将按钮的位置设置为输入下方,应将
btn.Left
和btn.Top
设置为相应的坐标。
Then when you need to work with generated Control/Button you can do search by that Name
in the following way: 然后,当您需要使用生成的控件/按钮时,可以通过以下方式按该
Name
进行搜索:
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()
. 如果您输入的Name不正确,则会在
.First()
上引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.