方案: 我通过后面的c#代码动态地向我的页面添加了一个asp文本框控件。 我有一个删除该文本框的按钮,用文本框中的文本替换它。
问题: 当我按下按钮时,page_init-> page_load-> page_prerender序列开始,擦除我的文本框控件。
我通过page_prerender中的方法初始化文本框。
我可以使用viewstate来保存值,但是看到有一个启用视图状态等。在回发中持久保存动态控件textbox.text属性的标准方法是什么?
代码我必须约会
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
else
{
add_tb();
}
}
private void add_tb()
{
Textbox tb = new Textbox();
pnlButtons.add(tb); //this is a panel init'd at design time which also includes a button
}
protected void imgBtn_Click_home(object sender, ImageClickEventArgs e)
{
lblTest.Text=tb.Text; // where do i declare the tb to access it from here and to persist it?
}
另外,我在哪里声明tb从这里访问它并坚持下去?
答案 0 :(得分:1)
您不显示代码。我会用语言回答你。
您应该始终添加控件,这发生在CreateChildControl Method
上 TextBox txt;
protected override void CreateChildControls()
{
base.CreateChildControls();
txt = new TextBox();
txt.ID = "textBoxTest";
txt.Visible = false;
pnlButtons.add(txt); // till now pnlButtons should be created because you call first for base.CreateChildControls
}
如果你想让控件在某些情况下没有“添加”,你可以默认将它显示为false。
之后当你要去OnPreRender
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if(condition)//condition is when you show your checkbox
{
txt.Visible = true;
lblTest.Visible = false;
}
else
{
lblTest.Visible = true;
txt.Visible = false;
}
}
以正确的方式显示控件。当控件可见时,false不会添加到页面中。您可以在页面的查看源中进行检查。之后不会出现像你这样的问题!