我已经看到了一些线索。如果我在页面加载时在更新面板中有一个控件,我可以使用以下代码轻松获取它:
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);
基本上我正在创建一个标签并将其放在一个更新面板中,然后在第二个按钮上单击我将其移动到另一个更新面板。每次我尝试这个,它说: 值不能为空。 参数名称:child
我也尝试过ControlCollection cbb = upPreview.ContentTemplateContainer.Controls;
同样的错误。任何想法?
答案 0 :(得分:0)
点击Label lbl
时,您的Button
在部分回发期间迷路了。您可以使用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.";
}
}
这样你就可以在回发期间跟踪它。