2015-11-04 61 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');"); }