在运行时从变量创建标签

时间:2016-01-04 19:24:37

标签: c#

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

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

一些帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

尝试这样,创建一个函数,使数组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();
}