设计如图:
打开源:
<body>
<form id="form1" runat="server">
<div>
省份:<asp:DropDownList ID="ddlProvince" runat="server"
onselectedindexchanged="ddlProvince_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
城市: <asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
建立数据库访问DBHelper类GetDataTable方法
public static DataTable GetDataTable(string sql)
{
SqlConnection conn = new SqlConnection("server=.;database=Provinces;uid=sa;pwd=sa2005");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
return dt;
}
DropDownList后置cs文件:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BingdingDDLProvince();
BingdingDDLCity();
}
}
/// <summary>
/// 绑定省份
/// </summary>
protected void BingdingDDLProvince()
{
string sql = "select * from province";
this.ddlProvince.DataSource = DBHelper.GetDataTable(sql);
this.ddlProvince.DataTextField = "ProName";
this.ddlProvince.DataValueField = "ProId";
this.ddlProvince.DataBind();
}
protected void BingdingDDLCity()
{
string sql = "select cityName from city where cityId='"+ this.ddlProvince.SelectedValue +"'";
this.ddlCity.DataSource = DBHelper.GetDataTable(sql);
this.ddlCity.DataTextField = "cityName";
this.ddlCity.DataBind();
}
//双击省份DropDownList控件
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string id = this.ddlProvince.SelectedValue;
string sql = "select * from city where cityId="+id;
Response.Write(sql);
this.ddlCity.DataSource = DBHelper.GetDataTable(sql);
this.ddlCity.DataTextField = "cityName";
this.ddlCity.DataBind();
}
}
运行结果: