我的有关在循环中动态创建标签的代码无效,只有一个出现

时间:2019-02-15 10:20:38

标签: c# winforms user-controls controls

我正在创建一个应用程序,在其中为txt文件(其中写有一些文本的中的每个字符)创建并写入一个包含来自txt的字符的标签。 在txt文件中,写入了“ Hello”,只有 H 出现

这是我的实际代码:

string test = System.IO.File.ReadAllText(@"../../../../../Texte/Test.txt");
int x = 20;
int y = 20;
int i = 10;

foreach (char ch in test) {
    Label newlabel = new Label();
    newlabel.Location = new System.Drawing.Point(x + i, y);
    newlabel.Text = ch.ToString();
    panel1.Controls.Add(newlabel);
    i += 15;
}

1 个答案:

答案 0 :(得分:3)

您应该将标签的AutoSize属性设置为TRUE。如果不设置此属性,则第一个标签将覆盖其余的标签,因此您只能看到第一个标签。请尝试以下操作:

foreach (char ch in test) {
    Label newlabel = new Label();
    newlabel.Location = new System.Drawing.Point(x + i, y);
    newlabel.Text = ch.ToString();
    newlabel.AutoSize = true; 
    panel1.Controls.Add(newlabel);
    i += 15;
}