3

我在同一个 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();
}

两者都使用一些服务器端代码由数据库记录项填充。现在,“ddlM”的 OnSelectedIndexChanged 事件我想选择“ddlC”的第一个索引,但不触发事件 ddlC_SelectedIndexChanged。对于“ddlC”,与“ddlC”的 OnSelectedIndexChanged 事件相同,我想选择“ddlM”的第一个索引,但不触发事件 ddlM_SelectedIndexChanged。不对,它会触发事件。我该怎么做才能防止它?

谢谢

4

2 回答 2

4

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

 ddlM.SelectedIndexChanged -= ddlM_SelectedIndexChanged;

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

 ddlM.SelectedIndexChanged += ddlM_SelectedIndexChanged;

然后你不必弄乱全局标志

于 2012-05-09T13:11:17.910 回答
3

在这种情况下,我们创建一个全局bool标志并将其值设置为truebefore changed SelectedIndexChanged。并在另一个控件中SelectedIndexChanged检查其值是否为真。如果为真,我们将它返回到事件之外。并在外面时再次更改标志值。确保始终将标志值更改回 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();            
}
于 2012-05-09T13:09:13.027 回答