2015-11-04 69 views
0

的label.text我添加标签与其相应的文字显示dinamically在ASP.NET编码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); 
     } 

该控件的占位符,工作正常dinamically出现,我的问题出来时,我尝试以检索的文本标签控件显示,为了做到这一点,我添加了一个按钮和编码下一

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

但调试应用程序时,我得到了错误

型“System.NullReferenceException”的异常出现在WebApplication2.dll但在用户代码中没有处理

能否请你帮我,告诉我如何从自动创建到标签的文本占位

+0

http://stackoverflow.com/questions/17589268/dynamically-created-controls-losing-data-after-postback在这里似乎是一个非常类似的问题。 –

+0

@JBKing你好,是的,只是检查了链接,现在我可以从标签中检索文本属性,只需将我的代码粘贴到Load事件中,但是如果我这样做了,页面就会像使用其控件加载普通页面我需要的是,当用户点击一个按钮时,占位符添加并自动显示控件,任何想法? –

+0

我会小心你期望页面在不同时间处于什么样的状态,这可能是问题所在。有可能不止一些解决方案,但我似乎记得当我遇到这种问题时,必须在过去几次重新创建动态控制。 –

回答

1

更换PlaceHolder1.FindControl( “lbdin”)作为标签,含:

var lbdin = PlaceHolder1.Children.Cast<Control>().FirstOrDefault(x => x.Id == "lbdin") as Label; 

,那么你需要测试空。

if(lbdin != null) 
{ 
    lbdin.Text = "Your Text"; 
} 
else 
{ Response.Write("alert('could not find label');"); }