使用:.NET 3.5SP1、VS2008
我正在编辑其他人的 asp.net 脚本,他在页面未回发时在 Page_Load
进行数据检索。
即使在页面中刷新、导航、回发后,我也可以看到数据已正确填充到 DropDownList 中。
我在脚本中添加了更多 DropDownList 和一些 CheckBox,只有我添加的 DropDownList 得到了正确填充。但不是 CheckBox。
于是我在一个新的项目中做了一个测试,和它的脚本结构类似:
ASPX:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
</asp:DropDownList>
<%
if (DropDownList1.SelectedValue == "Item2")
{
%>
<asp:CheckBox ID="CheckBox1" runat="server" Text="CheckBox 1" />
<asp:TextBox ID="TextBox1" runat="server" Text="" />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
</asp:DropDownList>
<%
}
%>
</div>
</form>
代码隐藏:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.CheckBox1.Checked = true;
this.CheckBox1.Text = "Hello CheckBox";
this.TextBox1.Text = "Hello TextBox";
this.DropDownList2.SelectedValue = "Item2";
}
}
}
所以正如您看到的代码,当页面首次加载时,CheckBox1
的文本将更改,Checked
将为真,因此其他 TextBox
和 DropDownList2
当我选择 DropDownList1
的项目到 Item2
时,当 CheckBox1
, TextBox1
, DropDownList2
除了 CheckBox1.Text
之外,什么都没有设置。
为什么会这样?
编辑:
我试图将它们放入面板中,这样就可以了。但问题是我正在编辑的程序使用上面的格式..所以我不允许将它们全部更改为面板。
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
</asp:DropDownList>
<%
if (DropDownList1.SelectedValue == "Item2")
{
this.MyPanel.Visible = true;
}
else
{
this.MyPanel.Visible = false;
}
%>
<asp:Panel ID="MyPanel" runat="server" Visible="false" >
<asp:CheckBox ID="CheckBox1" runat="server" Text="CheckBox 1" />
<asp:TextBox ID="TextBox1" runat="server" Text="" />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
</asp:DropDownList>
</asp:Panel>
</div>
</form>
最佳答案
尝试设置 EnableViewState
和 ViewStateMode
,也许某些父控件已将其禁用,因此已应用默认继承值。
MSDN :
The default value of the ViewStateMode property for a Web server control in a page is Inherit. As a result, if you do not set this property at either the page or the control level, the value of the EnableViewState property determines view-state behavior.
<asp:CheckBox ID="CheckBox1" runat="server" Text="CheckBox 1"
EnableViewState="true"
ViewStateMode="Enabled" />
关于c# - 为什么我的 CheckBox.Checked 属性会重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9726999/