标签:
相信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>
<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True"></asp:DropDownList> 
   (2)事件也注册了
 this.DropDownList1.SelectedIndexChanged += new System.EventHandler(this.DropDownList1_SelectedIndexChanged);
this.DropDownList1.SelectedIndexChanged += new System.EventHandler(this.DropDownList1_SelectedIndexChanged); 
    (3)事件也写了  
  
 private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e) 
 {
        { 
 Response.Write(this.DropDownList1.SelectedItem);
            Response.Write(this.DropDownList1.SelectedItem); 
 }
        } 
   
怎么还是不能输出选定项?进行调试发现不能进入SelectedIndexChanged事件。 
其实还有一种可能,就是你为DropDownList的不同option设置了相同的value 
比如后台这么写: 
 if(!IsPostBack)
if(!IsPostBack) 
 {
            { 
 for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value"));
                for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value")); 
 }
            } 
   
这样不会触发SelectedIndexChanged事件,修改成 
   
 if(!IsPostBack)
if(!IsPostBack) 
 {
            { 
 for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),i.ToString()));
                for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),i.ToString())); 
 }
            } 
       
一切些正常,根据msdn的解释: 
ListControl.SelectedIndexChanged 事件 
当列表控件的选定项在信息发往服务器之间变化时发生 
这不同于js的onchange事件,改为 
       
 if(!IsPostBack)
    if(!IsPostBack) 
 {
            { 
 for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value"));
                for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value")); 
 this.DropDownList1.Attributes.Add("onchange","alert(‘test‘);");
                this.DropDownList1.Attributes.Add("onchange","alert(‘test‘);"); 
 }
            } 
           测试可知。
DropDownList 控件不能触发SelectedIndexChanged 事件
标签:
原文地址:http://www.cnblogs.com/xiaoma-qi/p/5508407.html