参考资料:https://blog.csdn.net/liu_111111/article/details/8243567
数据库准备
从左到右分别为[pro]表(省)、[city]表(市)、[dis]表(区)。
前端代码
|
|
后台代码
public static SqlConnection DBConn()
{
return new SqlConnection("server=;database=;uid=;pwd=");//连接数据库
}
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)//第一次进入页面
{
bindpro();
}
}
private void pro()//读取省
{
SqlConnection conn = DBConn();
string sqlpro = "select pro_id,pro_name from [pro] ";
SqlCommand procmd = new SqlCommand(sqlpro, conn);
SqlDataAdapter myda0 = new SqlDataAdapter(procmd);
DataTable mydt0 = new DataTable();
myda0.Fill(mydt0);
DropDownList1.DataSource = mydt0;
DropDownList1.DataTextField = "pro_name";
DropDownList1.DataValueField = "pro_id";
DropDownList1.DataBind();
}
private void city()//读取市
{
SqlConnection conn = DBConn();
string sqlcity = "select city_name,city_id from [city] where pro_id = '" + DropDownList1.SelectedValue + "'";
SqlCommand citycmd = new SqlCommand(sqlcity, conn);
SqlDataAdapter myda = new SqlDataAdapter(citycmd);
DataTable mydt = new DataTable();
myda.Fill(mydt);
DropDownList2.DataSource = mydt;
DropDownList2.DataValueField = "city_id";
DropDownList2.DataTextField = "city_name";
DropDownList2.DataBind();
}
private void dis()//读取区
{
SqlConnection conn = DBConn();
string sqldis = "select dis_name,dis_id from [dis] where city_id = '" + DropDownList2.SelectedValue + "'";
SqlCommand discmd = new SqlCommand(sqldis, conn);
SqlDataAdapter myda1 = new SqlDataAdapter(discmd);
DataTable mydt1 = new DataTable();
myda1.Fill(mydt1);
DropDownList3.DataSource = mydt1;
DropDownList3.DataValueField = "dis_id";
DropDownList3.DataTextField = "dis_name";
DropDownList3.DataBind();
}
private void bindpro()//第一次进入页面时加载所有省市区第一位数据
{
pro();
city();
dis();
x1.Text = DropDownList1.SelectedItem.Text;
x2.Text = DropDownList2.SelectedItem.Text;
x3.Text = DropDownList3.SelectedItem.Text;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)//选择新省
{
city();
dis();
x1.Text = DropDownList1.SelectedItem.Text;
x2.Text = DropDownList2.SelectedItem.Text;
x3.Text = DropDownList3.SelectedItem.Text;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)//选择新市
{
dis();
x2.Text = DropDownList2.SelectedItem.Text;
x3.Text = DropDownList3.SelectedItem.Text;
}
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)选择新区
{
x3.Text = DropDownList3.SelectedItem.Text;
}
一些问题:你可能注意到在pro()、city()、dis()中并没有使用conn.Open();和conn.Close();,但是这却能成功运行,查阅资料后我发现原因在于SqlDataAdapter是自动打开自动释放的。不过我想使用Open()和Close()应该是一个好的习惯吧。