asp.net C# 可防止在从服务器端代码更改索引时触发 selectedindexchanged 事件

本文关键字:索引 事件 selectedindexchanged 代码 net 可防止 服务器端 asp | 更新日期: 2023-09-27 18:33:33

我在同一个aspx页面上有两个下拉列表控件

<asp:DropDownList ID="ddlM" runat="server" Width="123px" AutoPostBack="True" OnSelectedIndexChanged="ddlM_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="ddlC" runat="server" Width="123px" AutoPostBack="True" OnSelectedIndexChanged="ddlC_SelectedIndexChanged">
</asp:DropDownList>

两者的 OnSelectedIndexChanged 的 C# 代码如下所示:

protected void ddlC_SelectedIndexChanged(object sender, EventArgs e)
{
   ddlM.SelectedIndex = 0;
   ViewState["ddlC"] = true;
   ViewState["ddlM"] = false;                 
   BindPGrid();            
}
protected void ddlM_SelectedIndexChanged(object sender, EventArgs e)
{
   ddlC.SelectedIndex = 0;                
   ViewState["ddlC"] = false;
   ViewState["ddlM"] = true; 
   BindPGrid();
}

两者都由使用某些服务器端代码的数据库记录项填充。现在,OnSelectedIndexChanged 事件 "ddlM" 我想选择"ddlC"的第一个索引,但不触发事件ddlC_SelectedIndexChanged。与"ddlC"相同的"ddlC"的OnSelectedIndexChanged事件,我想选择"ddlM"的第一个索引,但不触发事件ddlM_SelectedIndexChanged。对,它触发了事件。我该如何防止它?

谢谢

asp.net C# 可防止在从服务器端代码更改索引时触发 selectedindexchanged 事件

或者,

可以从控件中删除并重新添加 SelectedIndexChanged 事件处理程序

 ddlM.SelectedIndexChanged -= ddlM_SelectedIndexChanged;
 ddlM.SelectedIndex = 0;
 ViewState["ddlC"] = false;
 ViewState["ddlM"] = true; 
 BindPGrid();
 ddlM.SelectedIndexChanged += ddlM_SelectedIndexChanged;

那么你就不必弄乱全局标志

在这种情况下,

我们创建一个全局bool标志,并在更改SelectedIndexChanged之前将其值设置为 true 。在另一个控件的SelectedIndexChanged检查其值是否为真。如果为 true,我们将在事件外部返回它。并在外面再次更改标志值。确保始终将标志值更改回 false,否则如果该事件由同一控件生成,则永远不会触发该事件。

boool flag = false;
protected void ddlC_SelectedIndexChanged(object sender, EventArgs e)
{
   flag = true;
   ddlM.SelectedIndex = 0;
   flag = false;
   ViewState["ddlC"] = true;
   ViewState["ddlM"] = false;                 
   BindPGrid();            
}
protected void ddlM_SelectedIndexChanged(object sender, EventArgs e)
{
   if(flag)
       return;
   ddlC.SelectedIndex = 0;                
   ViewState["ddlC"] = false;
   ViewState["ddlM"] = true; 
   BindPGrid();
}

或者您可以删除事件处理程序,例如

protected void ddlC_SelectedIndexChanged(object sender, EventArgs e)
{
   ddlM.SelectedIndexChanged -= ddlM_SelectedIndexChanged;
   ddlM.SelectedIndex = 0;
   ddlM.SelectedIndexChanged += ddlM_SelectedIndexChanged;
   ViewState["ddlC"] = true;
   ViewState["ddlM"] = false;                 
   BindPGrid();            
}