DropDownList的SelectedIndexChanged事件搞糊涂了
现在想完成这样一个操作,用DropDownList的选择项来控制Label的显示.如果为第一项时隐藏,第二项时显示.设置了DropDownList1_SelectedIndexChanged事件,在把DropDownList的autopostback属性设置为true的时候,通过在DropDownList选择来改变SelectedIndex是可以触发SelectedIndexChanged事件的,但我如果通过一个Button来设置DropDownList的SelectedIndex为0的时候它不触发这个事件.不明白了.我这里用代码也改变了DropDownList的SelectedIndex,为什么就不触发SelectedIndexChanged事件呢?是不是事件执行顺序的问题?
测试代码如下:
<form id= "form1 " runat= "server ">
<asp:DropDownList ID= "DropDownList1 " runat= "server " OnSelectedIndexChanged= "DropDownList1_SelectedIndexChanged "
Width= "171px ">
<asp:ListItem> 1 </asp:ListItem>
<asp:ListItem> 2 </asp:ListItem>
<asp:ListItem> 3 </asp:ListItem>
</asp:DropDownList>
<asp:Label ID= "Label1 " runat= "server " Text= "adsgasgasg " Visible= "False " Width= "232px "> </asp:Label>
<br />
<br />
<asp:Button ID= "Button1 " runat= "server " OnClick= "Button1_Click " Text= "Button " />
</form>
-----------------------------------------------------
后台
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.DropDownList1.SelectedValue == "1 ")
{
this.Label1.Visible = false;
}
else
{
this.Label1.Visible = true;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.DropDownList1.SelectedValue = "1 ";
}
[解决办法]
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ChangeText();
}
protected void Button1_Click(object sender, EventArgs e)
{
this.DropDownList1.SelectedValue = "1 ";
ChangeText();
}
private void ChangeText()
{
if (this.DropDownList1.SelectedValue == "1 ")
{
this.Label1.Visible = false;
}
else
{
this.Label1.Visible = true;
}
}