2013-03-26 102 views
2

我在這裏看到了一些線程。如果我在當頁面加載更新面板控制,我可以很容易地用下面的代碼獲得它:在更新面板中查找控件

Label lbls = (Label)upPreview.FindControl(lbl.ID); 
    lbls.Text = lbl.ID; 

什麼我不能做的是在兩個不同的更新面板兩個不同的按鈕下面

按鈕1:

Label lbl = new Label(); 
    lbl.Text = "something"; 
    lbl.ID = "something"; 
    upPreview.ContentTemplateContainer.Controls.Add(lbl); 

按鈕2

Label lbls = (Label)upPreview.FindControl(lbl.ID); 
    lbls.Text = lbl.ID; 
    upForm.ContentTemplateContainer.Controls.Add(lbls); 

基本上我CREA將標籤放在一個更新面板中,然後在第二個按鈕上單擊我將它移動到另一個更新面板。每次我嘗試這個時,它都會顯示: 值不能爲空。 參數名稱:孩子

我也試過ControlCollection cbb = upPreview.ContentTemplateContainer.Controls;

同樣的錯誤。有任何想法嗎?

+0

下面的答案是否爲您解決了這個問題?如果是這樣,請將問題標記爲已回答。 – McCee 2013-04-12 20:37:01

回答

0

當點擊Button時,您的Label lbl在部分回發期間丟失。您可以使用ViewState在回發期間保留它。

在您的Page_Load上添加一個單獨的Label並將其實例化爲null。

protected Label lbl = null; 

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) // First load or reload of the page 
    { 
     lbl = new Label(); 
     lbl.Text = "something"; 
     lbl.ID = "something"; 
     upPreview.ContentTemplateContainer.Controls.Add(lbl);   
    } 
    else 
    { 
     // Reinitialize the lbl to what is stored in the view state 
     if (ViewState["Label"] != null) 
      lbl = (Label)ViewState["Label"]; 
     else 
      lbl = null; 
    } 
} 

然後在您的Button_Click事件:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    // Save the lbl in the ViewState before proceeding. 
    ViewState["Label"] = lbl; 
} 

protected void Button2_Click(object sender, EventArgs e) 
{ 
    if (lbl != null) 
    { 
     // Retreive the lbl from the view state and add it to the other update panel 
     upForm.ContentTemplateContainer.Controls.Add(lbl);   
    } 
    else 
    { 
     lbl = new Label(); 
     lbl.Text = "Error: the label was null in the ViewState."; 
    } 
} 

這樣你跟蹤它在後背上。