在运行时从变量创建标签

本文关键字:创建 标签 变量 运行时 | 更新日期: 2023-09-27 18:28:53

我试图在运行时创建一个标签。标签的数量取决于另一个变量的项目数量,并且标签不显示。代码如下。

int NoofItems = tillfrm.lvbasket.Items.Count;  
for (int i = 0; i < NoofItems + 1; i++)  
{  
    Label lblitems = new Label();  
    lblitems.Name = "lblItems" + i;  
    lblitems.Font = new Font ("Calibri",lblitems.Font.Size);  
    lblitems.Location = new Point(95, (152 + (19 * i)));  
    lblitems.ForeColor = System.Drawing.Color.Black;  
    lblitems.Show();  
    lblitems.AutoSize = true;  
    lblitems.Text = tillfrm.lvbasket.Items[0].Text;  
    this.Controls.Add(lblitems);  
}

如有帮助,不胜感激。

在运行时从变量创建标签

您应该将tillfrm.lvbasket.Items[0].Text更改为tillfrm.lvbasket.Items[i].Text

以及i < NoofItems + 1i < NoofItems,因为数组大小是NoofItems

这样尝试,创建一个函数,使数组GLOBAL,

protected void myFunction()
{
int NoofItems = tillfrm.lvbasket.Items.Count;  
    for (int i = 0; i < NoofItems; i++)  
    {  
    Label lblitems = new Label();  
    lblitems.Name = "lblItems" + i;  
    lblitems.Font = new Font ("Calibri",lblitems.Font.Size);  
    lblitems.Location = new Point(95, (152 + (19 * i)));  
    lblitems.ForeColor = System.Drawing.Color.Black;  
    lblitems.Show();  
    lblitems.AutoSize = true;  
    lblitems.Text = tillfrm.lvbasket.Items[i].Text;  
    this.Controls.Add(lblitems);  
    }
}

然后在Form_load()函数或Page_load

protected void Form_Load(Object sender , EventArgs e)
{
   myFunction();
}