我正在为我的应用程序使用vs2012(C#),我正在寻找一种方法将标签和文本框动态地添加到表单上的tabPage中。但由于要添加的控件数量可能大于10,我还尝试将它们添加到“列”中,因此容器控件只会水平滚动,而不是垂直滚动。
例如,我正在尝试做这样的事情:
LabelControl LabelControl LabelControl LabelControl
TextboxControl TextboxControl TextboxControl TextboxControl
LabelControl LabelControl LabelControl LabelControl
TextboxControl TextboxControl TextboxControl TextboxControl
etc.
“容器”控件是一个TabPage,所以我知道我必须抓住它的高度并使用它。我可以让文本框呈现,但是标签控件在顶部有困难,然后是下面的文本框。
这是我到目前为止所得到的:
int height = tabPageBicycle.Height;
Point startLocation = new Point(0, 0);
int previousX = 0;
int previousY = 0;
int currentX = 0;
for (int x = 0; x < 75; x++)
{
Label label = new Label();
TextEdit text = new TextEdit();
label.Text = x.ToString();
text.Text = x.ToString();
label.Location = new Point(currentX, previousY);
tabPageBicycle.Controls.Add(label);
if ((height - previousY) < text.Height)
{
currentX += 100;
previousY = 0;
}
text.Location = new Point(currentX + text.Height + 5, previousY + 50);
previousX = text.Location.X;
previousY = text.Location.Y;
tabPageBicycle.Controls.Add(text);
}
关于我做错了什么的线索?
答案 0 :(得分:0)
在逐行完成并查看循环中正在进行的操作之后,将其弄清楚。这是我使用的最终代码....一如既往,我愿意接受建议/评论等。如何使其更好/更有效率。
int labelY = 0;
int textY = 0;
int startX = 5;
int startY = 5;
int height = tabPageBicycle.Height;
Point startLocation = new Point(0, 0);
for (int x = 0; x < 75; x++)
{
Label label = new Label();
TextEdit text = new TextEdit();
label.AutoSize = true;
label.Text = x.ToString();
text.Text = x.ToString();
//Determine if the next set of controls will be past the height of the container.
//If so, start on the next column (change X).
if ((height - textY) < ((label.Height + 10) + text.Height))
{
startX += 125;
labelY = 0;
}
//Start of new column.
if (labelY == 0)
label.Location = new Point(startX, startY);
else
label.Location = new Point(startX, textY + label.Height + 10);
tabPageBicycle.Controls.Add(label);
labelY = label.Location.Y;
textY = labelY + 15;
text.Location = new Point(startX, textY);
textY = text.Location.Y;
tabPageBicycle.Controls.Add(text);
}
结果:
我希望它可以帮助其他人!