页面文件
View Code
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>城市1</asp:ListItem>
<asp:ListItem>城市2</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
程序文件
View Code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text == "城市1")
{
DropDownList2.Items.Clear(); DropDownList2.Items.Add("区1"); DropDownList2.Items.Add("区2");
}
else if (DropDownList1.SelectedItem.Text == "城市2")
{
DropDownList2.Items.Clear(); DropDownList2.Items.Add("区3"); DropDownList2.Items.Add("区4");
}
}
注意第一个dropdownlist的AutoPostBack="True"一定要设置 其实如果这种省市区联动的一般不用数据库,直接在js里面写,或者找现成的有很多, 放数据库里浪费服务器资源,而且刷新效果不好。
提供一个比较好的省市三级联动的DropDownList+Ajax的三种框架(aspnet/Jquery/ExtJs) 示例:http://www.cnblogs.com/downmoon/archive/2010/06/15/1758675.html
附加一个使用数据库数据的例子:
前台控件代码:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"> <asp:Label ID="Label1" runat="server" Text="模块:"></asp:Label> <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True"> </asp:DropDownList> <asp:Label ID="Label2" runat="server" Text="分类:" Visible="false"></asp:Label> <asp:DropDownList ID="DropDownList2" Visible="false" runat="server"> </asp:DropDownList> </asp:PlaceHolder>
后台代码段:
protected string SqlModuleList = ""; protected string SqlTypeList = ""; SqlHelper sqlhelper = new SqlHelper(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ModuleList(); //首次加载模块的下拉数据 } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if (DropDownList1.SelectedItem.Text != "") { SqlTypeList = "select TypeID,TypeName from KY_SendMessage_Type as T,KY_SendMessage_Module as M where T.ModuleID=M.ModuleID and T.ModuleID=" + DropDownList1.SelectedValue + ""; DataSet ds = sqlhelper.readDataSet(SqlTypeList); DataTable dt = ds.Tables[0]; if (dt.Rows.Count != 0)//判断模块下面是否有子分类 { Label2.Visible = true; DropDownList2.Visible = true; DropDownList2.Items.Clear(); } else { Label2.Visible = false; DropDownList2.Visible = false; } DropDownList2.DataSource = dt; DropDownList2.DataValueField = "TypeID"; DropDownList2.DataTextField = "TypeName"; DropDownList2.DataBind(); } } protected void ModuleList() { SqlModuleList = "select * from KY_SendMessage_Module as M"; DataSet ds = sqlhelper.readDataSet(SqlModuleList); DataTable dt = ds.Tables[0]; DropDownList1.DataSource = dt; DropDownList1.DataValueField = "ModuleID"; DropDownList1.DataTextField = "ModuleName"; DropDownList1.DataBind(); }
部分效果图:
初始加载图
点击选项加载子下拉图
|
请发表评论