【问题标题】:couple of problems for those controls dynamically created in the page_init在 page_init 中动态创建的那些控件的几个问题
【发布时间】:2013-09-06 21:33:44
【问题描述】:

基于某些条件,我在 Page_Init() 中动态创建了一些复选框、下拉列表和文本框。在同一页面中,我有一个在设计时(在 aspx 页面中)创建的提交按钮。以下是部分代码。文本框的可见性由复选框控制。

现在我有两个问题需要解决: (1) ddl.selectedIndex 总是初始化为 0 而不是 -1。但是在事件处理程序 Sumbit_Click() 中,即使我没有选择任何项目,ddl.selectedIndex 也是 0。 (2) 即使复选框被选中,在回发期间,文本框也不显示。有什么办法可以解决吗?

DropDownList ddl = new DropDownList();
ddl.ID = "ddl" + id;
ddl.DataSource = subCallReasonEntityList;
ddl.DataTextField = "myText";
ddl.DataValueField = "id";                          
ddl.DataBind();
ddl.SelectedIndex = -1;
cell.Controls.Add(ddl);

CheckBox cb = new CheckBox();
cb.ID = "cb" + id;
cb.ClientIDMode = ClientIDMode.Static;
cell.Controls.Add(cb);
cell.Controls.Add(new LiteralControl("<br />"));

TextBox tb = new TextBox();
tb.ID = "txt" + id;
tb.ClientIDMode = ClientIDMode.Static;
tb.Attributes.Add("style", "display:none");
cb.Attributes.Add("onclick", "return cbOtherClicked('" + cb.ClientID + "', '" + tb.ClientID + "')");
cell.Controls.Add(tb);

function cbOtherClicked(control1, control2) {
var cbOther = document.getElementById(control1);
var txtOther = document.getElementById(control2);

if (cbOther.checked) {
    txtOther.style.display = "block";
}
else {
    txtOther.style.display = "none";
}
}

【问题讨论】:

标签: asp.net page-init


【解决方案1】:

这里的问题是您的动态控件没有维护 ViewState。

KEY: 将控件添加到表单/页面等后修改。如果您在将属性添加到表单之前修改属性,则添加的值不会进入 viewState 并且会在回发时丢失。至少要做到这一点。

所以,这样做:

DropDownList ddl = new DropDownList();
// add first this control 
cell.Controls.Add(ddl);
// now set the values
ddl.ID = "ddl" + id;
ddl.DataSource = subCallReasonEntityList;
ddl.DataTextField = "myText";
ddl.DataValueField = "id";                          
ddl.DataBind();
ddl.SelectedIndex = -1;

并确保您始终在每次回发时重新创建所有动态控件。

当我们动态添加任何控件时,一旦添加它们,它就会“追赶”页面生命周期。一旦控件被添加到“Controls”集合中,它错过的所有事件都会被触发。

由此得出一个非常重要的结论:您可以在页面生命周期中的任何时间添加动态控件,直到“PreRender”事件发生。即使您在“PreRender”中添加动态控件事件,一旦控件被添加到“Controls”集合中,“Init”、“LoadViewState”、“LoadPostbackdata”、“Load”和“SaveViewstate”就会为此控件触发。

【讨论】:

  • 我对我的代码进行了调整,但 SelectedIndex 仍然是 0。
  • 请确保仅在 Count 为零时才将项目添加到 DropDownlist。另请参考此链接:codebetter.com/jefferypalermo/2004/11/25/…
  • 我已经阅读了上面的链接,我想知道我是否需要进行调整,因为我的控件是在 Page_Init 而不是 Page_Load 中创建的?
猜你喜欢
  • 2011-04-30
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多