Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用变量在c#代码中创建win表单标签?_C#_Winforms_Variables_Label - Fatal编程技术网

使用变量在c#代码中创建win表单标签?

使用变量在c#代码中创建win表单标签?,c#,winforms,variables,label,C#,Winforms,Variables,Label,我用这段代码创建了一个新标签,标签上附加了一个变量,但是我得到了一个错误(很明显)。有办法做到这一点吗 System.Windows.Forms.Label lbl_Task[i] = new System.Windows.Forms.Label(); 也就是说,如果I==4,标签将被称为lbl_Task4。如果i==9,则为lbl_Task9,以此类推 编辑: 新代码显示: for (int i = 0; i < rows; i++) { //c

我用这段代码创建了一个新标签,标签上附加了一个变量,但是我得到了一个错误(很明显)。有办法做到这一点吗

System.Windows.Forms.Label lbl_Task[i] = new System.Windows.Forms.Label();
也就是说,如果I==4,标签将被称为lbl_Task4。如果i==9,则为lbl_Task9,以此类推

编辑:

新代码显示:

for (int i = 0; i < rows; i++)
        {
            //create a label for the Task Name
            Label lbl = new Label();
            lbl.Name = "lbl_Task" + i;
            tableLayoutPanel1.SetColumnSpan(lbl, 4);
            lbl.Dock = System.Windows.Forms.DockStyle.Fill;
            lbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            lbl.Location = new System.Drawing.Point(3, pointInt);
            lbl.Size = new System.Drawing.Size(170, 24);
            lbl.TabIndex = 8;
            lbl.Text = Convert.ToString(dtTasks.Rows[i]["Task_Name"]);
            lbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

            this.Controls.Add(lbl);
            pointInt += 24;
        }
for(int i=0;i

这会编译,但在调试时不会显示在win窗体上。有什么想法吗?

您正在寻找这样的想法:

for(int i =0; i<10; i++)
{
   Label lbl = new Label();
   lbl.Name = "lbl_Task" + i;
   // set other properties
   this.Controls.Add(lbl);
}

for(inti=0;i使用一组标签,然后像这样尝试

List<Label> labels = new List<Label>();
for (int i = 0; i < 100; i++)
{
    Label label = new Label();
    // Set Lable properties

    yourLayoutName.Controls.Add(label);//add the lable
    labels.Add(label);
}
列表标签=新列表();
对于(int i=0;i<100;i++)
{
标签=新标签();
//设置标签属性
yourLayoutName.Controls.Add(label);//添加标签
标签。添加(标签);
}

不要依赖标签的名称,而是使用属性来存储
i
,创建标签的方式是错误的。应该是:
System.Windows.Forms.Label lbl\u Task=new System.Windows.Forms.Label();lbl_Task.Tag=i;
不要编写这样的代码,除了出错之外,它的性能非常差。请改用ListBox或ListView。您将必须记录您使用TableLayoutPanel控件所做的操作以及标签控件与它的关系。@HansPassant所说的,或GDI+它。不过,通常我不会编写这样的代码r这是一个实验,看看是否可以这样做!