Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.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# 为什么控件是';面板中的s每次都会被覆盖吗?_C#_Asp.net - Fatal编程技术网

C# 为什么控件是';面板中的s每次都会被覆盖吗?

C# 为什么控件是';面板中的s每次都会被覆盖吗?,c#,asp.net,C#,Asp.net,每次触发按钮的click事件时,面板中的标签(或任何其他控件)都会被新标签覆盖!这是按钮事件 protected void Button3_Click(object sender, EventArgs e) { Label lbl = new Label(); lbl.ID = "name"; lbl.Text = Profession.SelectedItem.ToString(); Panel1.Controls.Add( lbl); } 每次删除上一个标签

每次触发按钮的click事件时,面板中的标签(或任何其他控件)都会被新标签覆盖!这是按钮事件

protected void Button3_Click(object sender, EventArgs e)
{
    Label lbl = new Label();
    lbl.ID = "name";
    lbl.Text = Profession.SelectedItem.ToString();
    Panel1.Controls.Add( lbl);
}

每次删除上一个标签并添加新标签时,它都会在DropDownList中的选定项目中进行初始化

protected void Button3_Click(object sender, EventArgs e)
{
    Label lbl = new Label();//here on every click new label initialized
    lbl.ID = "name";
    lbl.Text = Profession.SelectedItem.ToString();
    Panel1.Controls.Add(lbl);
}
将上述代码替换为

Label lbl = new Label();
protected void Button3_Click(object sender, EventArgs e)
{        
    lbl.ID = "name";
    lbl.Text = Profession.SelectedItem.ToString();
    if(!Panel1.Controls.Contains(lbl)) //Check here if label already added
         Panel1.Controls.Add(lbl);
}

查看标签的范围。每次单击都会创建新的Label实例。以班级为例

Label lbl = new Label();

为什么不在页面启动时将标签添加到面板中?只需在单击时更改标签文本。单击后我将添加多个标签。在用户按下按钮之前不想添加。@aravind:我不是用vb开发的。你可以在线使用一个代码转换器将vb转换成c#…逻辑可能是一样的。。