在網站注冊的頁面上經常要選擇注冊地點,如果改變省的名稱就能出現對應的市級的名稱,將為用戶帶來很大的方便,下面就將我的實現過程給大家看一下
首先,建立數據庫“Place”,表里面的內容如下圖所示:
窗體布局如下圖所示:
下面是實現代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace 省市聯動 { public partial class 省市聯動 : System.Web.UI.Page { string strCon = "server=.;database=Place;uid=sa;pwd=123456"; protected void Page_Load(object sender, EventArgs e) { //DropDownList1.Text = "北京市"; if (!IsPostBack) { SqlConnection sqlcon = new SqlConnection(strCon); string sqlstr = "select * from Province"; string strCity = "select * from City where Province = '北京市'"; SqlDataAdapter myda = new SqlDataAdapter(sqlstr, strCon); SqlDataAdapter mydaCity = new SqlDataAdapter(strCity, sqlcon); DataSet myds = new DataSet(); DataSet mydsCity = new DataSet(); sqlcon.Open(); myda.Fill(myds); mydaCity.Fill(mydsCity); DropDownList1.DataSource = myds; DropDownList1.DataValueField = "ProvinceName"; DropDownList1.DataBind(); DropDownList2.DataSource = mydsCity; DropDownList2.DataValueField = "CityName"; DropDownList2.DataBind(); sqlcon.Close(); } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { SqlConnection sqlcon = new SqlConnection(strCon); string sqlstr = "select * from City where Province = '" + DropDownList1.SelectedValue.Trim() + "'"; SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); DataSet myds = new DataSet(); sqlcon.Open(); myda.Fill(myds); DropDownList2.DataSource = myds; DropDownList2.DataValueField = "CityName"; DropDownList2.DataBind(); sqlcon.Close(); } } }
接下來運行就可以了
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
