2013-03-26 66 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."; 
    } 
} 

这样你跟踪它在后背上。