我添加了一个带有相应文本的标签,以便在ASP.NET编码C#中使用占位符进行dinamically显示,下一个片段是显示我暂时拥有的内容
protected void Button1_Click(object sender, EventArgs e)
{
Label label1= new Label();
label1.ID="lbdin";
label1.Text="agregado dinamicamente";
TextBox textbox1 = new TextBox();
textbox1.Text = "textbox dinamico";
Button btn = new Button();
btn.ID = "btn";
btn.Text = "boton dinamico";
btn.Click += DynamicButton;
PlaceHolder1.Controls.Add(label1);
PlaceHolder1.Controls.Add(textbox1);
PlaceHolder1.Controls.Add(btn);
}
控件在占位符中显示为dinamically,工作正常,当我尝试检索标签控件显示的文本时出现问题,为了做到这一点,我添加了一个按钮并编码了下一个< / p>
protected void Button2_Click(object sender, EventArgs e)
{
Label Referencia_lb = PlaceHolder1.FindControl("lbdin") as Label;
//Label Referencia_lb = PlaceHolder1.FindControl("lbdin") as Label;
Referencia_lb.Text = "CAMBIANDO EL TEXTO DEL OBJETO CREADO EN TIEMPO DE EJECUCION";
}
但是在调试应用程序时我得到了错误
类型&#39; System.NullReferenceException&#39;的例外情况发生在WebApplication2.dll中但未在用户代码中处理
你能不能请我帮忙,告诉我如何从自动创建的标签中检索文本
答案 0 :(得分:1)
将PlaceHolder1.FindControl(“lbdin”)替换为标签:
var lbdin = PlaceHolder1.Children.Cast<Control>().FirstOrDefault(x => x.Id == "lbdin") as Label;
然后你需要测试null。
if(lbdin != null)
{
lbdin.Text = "Your Text";
}
else
{ Response.Write("alert('could not find label');"); }