0

我正在为我的应用程序使用 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);
}

关于我做错了什么的任何线索?

4

1 回答 1

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);
}

结果: 在此处输入图像描述

我希望它可以帮助别人!

于 2013-04-23T11:01:42.223 回答