相信DropDownList 控件不能觸發SelectedIndexChanged 事件已經不是什么新鮮事情了,原因也無外乎以下幾種:
1、DropDownList 控件的屬性 AutoPostBack="True" 沒有寫;
2、DropDownList 控件的數據綁定沒有放在if (!Page.IsPostBack) 里面;
3、DropDownList 控件選定項的value 值只有在發生變化時,才將信息發往服務器;
有人問
(1)AutoPostBack="True"
<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True"></asp:DropDownList>
(2)事件也注冊了
this.DropDownList1.SelectedIndexChanged += new System.EventHandler(this.DropDownList1_SelectedIndexChanged);
(3)事件也寫了
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Response.Write(this.DropDownList1.SelectedItem);
}
怎么還是不能輸出選定項?進行調試發現不能進入SelectedIndexChanged事件。
其實還有一種可能,就是你為DropDownList的不同option設置了相同的value
比如后台這么寫:
if(!IsPostBack)
{
for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value"));
}
這樣不會觸發SelectedIndexChanged事件,修改成
if(!IsPostBack)
{
for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
一切些正常,根據msdn的解釋:
ListControl.SelectedIndexChanged 事件
當列表控件的選定項在信息發往服務器之間變化時發生
這不同於js的onchange事件,改為
if(!IsPostBack)
{
for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value"));
this.DropDownList1.Attributes.Add("onchange","alert('test');");
}
測試可知。