在C#中动态添加控件到循环下 [英] dynamically adding controls under loop in C#
本文介绍了在C#中动态添加控件到循环下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发Windows应用程序,我想在其中循环动态创建一些控件. 我正在尝试的代码是
I am developing a windows application where I want to create some controls dynamically inside a loop. The code I am trying is
private Label newLabel = new Label();
private int txtBoxStartPosition = 100;
private int txtBoxStartPositionV = 25;
for (int i = 0; i < 7; i++)
{
newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV);
newLabel.Size = new System.Drawing.Size(70, 40);
newLabel.Text = i.ToString();
panel1.Controls.Add(newLabel);
txtBoxStartPositionV += 30;
}
此代码仅生成一个带有文本7的标签,但是我想用它们各自的文本创建8个标签,我该怎么做?
This code is generating only one Label with text 7 but I want to create 8 Lables with their respective texts, how can I do this?
推荐答案
在您的循环中,您实质上是在更新同一Label的属性.如果要在每个步骤上创建一个新对象,请在循环内移动对象的创建:
In your loop you are essentially updating properties of the very same Label. If you want create a new one on each step, move creation of the object inside the loop:
private Label newLabel;
for (int i = 0; i < 7; i++)
{
newLabel = new Label();
...
如果想要 8 标签,您的for
应该迭代8次,而不是7次,就像现在这样:
By the way if you want 8 labels - your for
should iterate 8 times, not 7, as it does now:
for (int i = 0; i < 8; i++)
这篇关于在C#中动态添加控件到循环下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文