我在ASP.NET coding C#中添加了一个标签及其各自的文本,以动态地使用占位符显示,下一个代码片段将显示我暂时拥有的内容
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);
}控件以动态方式出现在占位符中,这很好用,当我试图检索label控件显示的文本时,我的问题就出来了,为此,我添加了一个按钮并编写了下一个按钮
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";
}但是在调试应用程序时,我得到了以下错误
WebApplication2.dll中出现类型为“System.NullReferenceException”的异常,但未在用户代码中进行处理
您能否帮助我并告诉我如何从自动创建到占位符中的标签中检索文本
发布于 2015-11-05 02:31:10
将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');"); }https://stackoverflow.com/questions/33529145
复制相似问题