六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 42|回复: 0

(摘抄)为什么设置了DropDownList的AutoPostBack="True"还是不能触发SelectedIndexC

[复制链接]

升级  40%

30

主题

30

主题

30

主题

秀才

Rank: 2

积分
110
 楼主| 发表于 2013-2-7 14:33:28 | 显示全部楼层 |阅读模式
曾经遇到过这个问题,后来在LoveCherry的博客中找到了更详细的解释。

该文地址:http://lovecherry.cnblogs.com/archive/2005/04/26/145705.html

原文如下:

有人问
(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');");
            }
测试可知。


您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表