[英]Create controls dynamically
I want to know if this is possible in c# winform. 我想知道c#winform中是否可行。
create control when ever button is pressed and place it at given location. 按下按钮时创建控件并将其放在给定位置。
I think it is possible like this 我认为有可能这样
private TextBox txtBox = new TextBox();
private Button btnAdd = new Button();
private ListBox lstBox = new ListBox();
private CheckBox chkBox = new CheckBox();
private Label lblCount = new Label();
but the problem lies when ever button is pressed same name controls are created.How to avoid that 但问题在于按下按钮时会创建相同的名称控件。如何避免这种情况
What da........ i wrote and no exception i was expecting it because control already contains btnAdd
instead as many button create as many you want. 什么da ........我写了,并没有异常我期待它因为控件已经包含
btnAdd
而不是许多按钮创建你想要的许多。 Accessing them will be issue but it will be solved by @drachenstern
method correct? 访问它们将是问题,但它将通过
@drachenstern
方法正确解决?
private void button1_Click_1(object sender, EventArgs e)
{
Button btnAdd = new Button();
btnAdd.BackColor = Color.Gray;
btnAdd.Text = "Add";
btnAdd.Location = new System.Drawing.Point(90, 25+i);
btnAdd.Size = new System.Drawing.Size(50, 25);
this.Controls.Add(btnAdd);
i = i + 10;
}
int currentNamingNumber = 0;
txtBox.Name = "txtBox" + currentNamingNumber++;
Rinse, Repeat. 冲洗,重复。
Gives each element a unique numeric name, allows you to find out how many elements have been created (notice that you don't want to decrement to track all created objects, because then you may create two elements with the same name). 为每个元素提供唯一的数字名称,允许您找出已创建的元素数量(请注意,您不希望减少以跟踪所有创建的对象,因为这样您可以创建两个具有相同名称的元素)。
I don't think you can pass the name you want into the new function, but you can always set the name after creating it. 我不认为你可以将你想要的名字传递给新功能,但你可以在创建它之后始终设置名称。
这听起来像是在寻找List<TextBox>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.