实现功能: 第一个DropDownList改变时,更新另外一个DropDownList和Label;第二个DropDownList改变时更新Label
前台设计:2个DropDownList ,2个UpdatePanel,1个Label,其中1个UpdatePanel包含1个DropDownList
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList runat="server" ID="DropDownList1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>我</asp:ListItem>
<asp:ListItem>你</asp:ListItem>
<asp:ListItem>他</asp:ListItem>
</asp:DropDownList>
<asp:UpdatePanel runat="server" ID="UpdatePanel2" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList runat="server" ID="DropDownList2" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="Label1" Text="来更新我啊"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged"/>
<asp:AsyncPostBackTrigger ControlID="DropDownList2" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
</div>
注意:ScriptManager控件必须在所有UpdatePanel控件之前,DropDownList改变时必须设置回发(AutoPostBack="True")
最重要的一点就是在使用UpdatePanel时,不能使用Response.Write(),否则将不能刷新,这是很致命的一点
后台代码:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedItem.Text;
if (DropDownList1.SelectedItem.Text == "我")
{
DropDownList2.Items.Clear();
DropDownList2.Items.Add("我1");
DropDownList2.Items.Add("我2");
DropDownList2.Items.Add("我3");
}
if (DropDownList1.SelectedItem.Text == "你")
{
DropDownList2.Items.Clear();
DropDownList2.Items.Add("你1");
DropDownList2.Items.Add("你2");
DropDownList2.Items.Add("你3");
}
if (DropDownList1.SelectedItem.Text == "他")
{
DropDownList2.Items.Clear();
DropDownList2.Items.Add("他1");
DropDownList2.Items.Add("他2");
DropDownList2.Items.Add("他3");
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList2.SelectedItem.Text;
}