(论坛答疑点滴)为什么设置了DropDownList的AutoPostBack="True"还是不能触发SelectedIndexChanged事件?

有人问
(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');");
            }

测试可知。

posted @   lovecherry  阅读(9110)  评论(8编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示