ASP.NET DropDownList

2024-12-29 09:59:09
推荐回答(3个)
回答1:




onselectedindexchanged="ddlProvince_SelectedIndexChanged">

onselectedindexchanged="ddlCity_SelectedIndexChanged">







cs代码:
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;

namespace Ganged
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}

//数据绑定
private void Bind()
{
using (SqlConnection con = new SqlConnection("server=.;database=ganged;uid=sa;pwd=sa;"))
{
con.Open();

//先初始化省

SqlCommand cmdPro = new SqlCommand("select ProID,ProName from T_Province", con);
SqlDataReader drPro = cmdPro.ExecuteReader();
this.ddlProvince.DataSource = drPro;
this.ddlProvince.DataTextField ="ProName";//显示值
this.ddlProvince.DataValueField = "ProID"; //显示主键
this.ddlProvince.DataBind();
drPro.Close();

//初始化市

SqlCommand cmdCity = new SqlCommand("select CityID,CityName from T_City where ProID='" + this.ddlProvince.SelectedValue + "'", con);
SqlDataReader drCity = cmdCity.ExecuteReader();
this.ddlCity.DataSource = drCity;
this.ddlCity.DataTextField = "CityName";
this.ddlCity.DataValueField = "CityID";
this.ddlCity.DataBind();
drCity.Close();

//初始化县

SqlCommand cmdDist = new SqlCommand("select id,DisName from T_District where CityID='" +this.ddlCity.SelectedValue + "'",con);
SqlDataReader drDist = cmdDist.ExecuteReader();
this.ddlDist.DataSource = drDist;
this.ddlDist.DataTextField = "DisName";
this.ddlDist.DataValueField = "id";
this.ddlDist.DataBind();
drDist.Close();
}

}

protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e) //DropDownList选中(省改变)产生的事件
{
string ProID = this.ddlProvince.SelectedValue;
using (SqlConnection con = new SqlConnection("server=.;database=ganged;uid=sa;pwd=sa;"))
{
con.Open();
SqlCommand cmdCity = new SqlCommand("select CityID,CityName from T_City where ProID='" + ProID + "'", con);
SqlDataReader drCity = cmdCity.ExecuteReader();
this.ddlCity.DataSource = drCity;
this.ddlCity.DataTextField = "CityName";
this.ddlCity.DataValueField = "CityID";
this.ddlCity.DataBind();
drCity.Close();
con.Close();
ddlCityBind();
}
}

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)//DropDownList选中(市改变)产生的事件
{
ddlCityBind();
}

private void ddlCityBind()
{
string CityID = this.ddlCity.SelectedValue;
using (SqlConnection con = new SqlConnection("server=.;database=ganged;uid=sa;pwd=sa;"))
{
con.Open();
SqlCommand cmdDist = new SqlCommand("select id,DisName from T_District where CityID='" + CityID + "'", con);
SqlDataReader drDist = cmdDist.ExecuteReader();
this.ddlDist.DataSource = drDist;
this.ddlDist.DataTextField = "DisName";
this.ddlDist.DataValueField = "id";
this.ddlDist.DataBind();
drDist.Close();
}
}
}
}

回答2:

你在省份的下拉列表的onchange事件里加载市的下拉列表

回答3:

这东东挺简单的,自己整整就出来了。