向TabPage添加控件,只添加第一个标签

时间:2017-05-12 11:19:23

标签: c# winforms tabpage

尝试向tabPage添加控件,只添加第一个标签,不确定问题,请检查

int X = 230;
int Y = 10;

ArrayList Lbls = new ArrayList();
Lbls.Add("Lbls_1");
Lbls.Add("Lbls_2");
Lbls.Add("Lbls_3");
Lbls.Add("Lbls_4");
Lbls.Add("Lbls_5");

foreach (object obj in Lbls)
{
    Label LblsAdd = new Label();
    LblsAdd.AutoSize = true;
    LblsAdd.Text = obj.ToString();
    LblsAdd.Left = X + 50;
    LblsAdd.Top = Y;
    LblsAdd.Size = new System.Drawing.Size(30, 15); 
    MyTabPage.Controls.Add(LblsAdd);
}

1 个答案:

答案 0 :(得分:1)

正如已经指出的那样,所有标签位于同一位置,因为在每次迭代时X仍然是230 + 50 = 280。 您需要增加此变量,以便对于下一个标签,您可以使用更新的结果:

foreach (object obj in Lbls)
{
    Label LblsAdd = new Label();
    LblsAdd.AutoSize = true;
    LblsAdd.Text = obj.ToString();
    X = X + 50;  // write a new value into the variable X
    LblsAdd.Left = X;
    LblsAdd.Top = Y;
    LblsAdd.Size = new System.Drawing.Size(30, 15); 
    MyTabPage.Controls.Add(LblsAdd);
}