頁面文件

<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>
程序文件

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();
}
部分效果圖:
初始加載圖
點擊選項加載子下拉圖