[code=C#<asp:DropDownList ID= "DropDownList1 " runat= "server " AutoPostBack= "True "
EnableViewState= "False " OnSelectedIndexChanged= "DropDownList1_SelectedIndexChanged ">
<asp:ListItem> 中文 </asp:ListItem>
<asp:ListItem> 英文 </asp:ListItem>
<asp:ListItem> 日语 </asp:ListItem>
</asp:DropDownList> protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write(DropDownList1.SelectedValue.ToString());
} ][/code]
我设置EnableViewState= "False " 为什么选择第一项(中文)的时候没反应呢?第二项第三项却正常执行选择事件(DropDownList1_SelectedIndexChanged)代码?
EnableViewState= "False " OnSelectedIndexChanged= "DropDownList1_SelectedIndexChanged ">
<asp:ListItem> 中文 </asp:ListItem>
<asp:ListItem> 英文 </asp:ListItem>
<asp:ListItem> 日语 </asp:ListItem>
</asp:DropDownList> protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write(DropDownList1.SelectedValue.ToString());
} ][/code]
我设置EnableViewState= "False " 为什么选择第一项(中文)的时候没反应呢?第二项第三项却正常执行选择事件(DropDownList1_SelectedIndexChanged)代码?
大概意思是说每次postback都会重新创建DropDownList,而设置EnableViewState为true,则会在OnPreInit中设置SelectedIndex为上次选择的。而设置EnableViewState为false,则会设置成默认的0.
因此选择第一个会被认为是没有改变,不会激发changed事件
The problem here is that when you set the EnableViewState to false, you have
reconstructed the dropdownlists on every postback. After reconstructing
them, (at the end of the OnPreInit), the selectedindex is always =0.
Therefore if you had changed the first dropdownlist (which fired the first
event) then changed the second dropdownlist, the event of the first would
still be fired because as far as the page is concerned you have changed both
dropdownlist from the time you reconstructed them.Your problem disappeared when you set the EnableViewState to true because
after the OnPreInit the state of the first dropdownlist (from previous
postback) changed the selectedIndex of your list and therefore the
dropdownlist did not sense a change in the selectedindex.
DropDownList1_SelectedIndexChanged不会执行
添加 <asp:ListItem Value=""> </asp:ListItem>
我觉得ViewState中记录的是修改之前的值,然后修改后的值在Form中被postback回来,再和之前记住的值比较,以决定是否fire SelectedChanged事件。记住,很多操作会激发postback,像点击button什么的。如果ViewState中记录的值和Form中Postback回来的值一样,就说明不是Dropdownlist激发的postback.