下面就是在提交按钮的单击事件中填写代码(代码区)(前提是把省市县的数据库建好)
protected void Page_Load(object sender, EventArgs e) { if (!this.Page.IsPostBack) { getddlProvinceDataBind(); //页面首次加载执行省份绑定
} } public void getddlProvinceDataBind() //省份数据绑定 { string sqlProvince = "SELECT * FROM province"; DropDownList2.DataSource = getDataSet(sqlProvince); DropDownList2.DataTextField = "province"; DropDownList2.DataValueField = "provinceID"; DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("--省份--", "0")); } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { //第一层,省份选择事件 { int ProvinceID = Convert.ToInt32(DropDownList2.SelectedValue); if (ProvinceID > 0) { string sqlCity = "SELECT * FROM city WHERE father=" + ProvinceID + ""; //根据省份ID找城市 DropDownList3.DataSource = getDataSet(sqlCity); DropDownList3.DataTextField = "city"; DropDownList3.DataValueField = "cityID"; DropDownList3.DataBind();
DropDownList3.Items.Insert(0, new ListItem("--请选择城市--", "0")); } else { DropDownList3.Items.Clear(); DropDownList3.Items.Insert(0, new ListItem("--请选择城市--", "0")); DropDownList3.Items.Clear(); DropDownList3.Items.Insert(0, new ListItem("--请选择县区--", "0")); } } }
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e) { //第二层,城市件 { int CityID = Convert.ToInt32(DropDownList3.SelectedValue); if (CityID > 0) { string sqlDistrict = "SELECT * FROM area WHERE father=" + CityID + ""; //根据城市ID找县区 DropDownList4.DataSource = getDataSet(sqlDistrict); DropDownList4.DataTextField = "area"; DropDownList4.DataValueField = "areaID"; DropDownList4.DataBind();
DropDownList4.Items.Insert(0, new ListItem("--请选择县区--", "0")); } else { DropDownList4.Items.Clear(); DropDownList4.Items.Insert(0, new ListItem("--请选择县区--", "0")); } } }
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e) { int ProvinceID = Convert.ToInt32(DropDownList2.SelectedValue); int CityID = Convert.ToInt32(DropDownList3.SelectedValue); int DistrictID = Convert.ToInt32(DropDownList4.SelectedValue); //if (ProvinceID > 0 && CityID > 0 && DistrictID > 0) //{ // Response.Write("您选择的省份ID:" + ProvinceID + "城市ID:" + CityID + "县区ID:" + DistrictID + ""); //} } public DataSet getDataSet(string sql) //自定义方法,sql语句参数,返回DataSet数据集 { string connection = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString; SqlConnection conn = new SqlConnection(connection); SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sda.Fill(ds); return ds; }
这样,就完成我们想要的效果了。如下图所示: