当第一个DropDownList中的数据变动时,触发 事件onselectedindexchanged,在这个事件中完成对第二个DropDownList的数据绑定;
示例:城市和省份的联动
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BingdingDDLProvince();
BingdingDDLCity();
}
}
//省份变动事件
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string id = this.ddlProvince.SelectedValue;
string sql = "select * from 城市表 where 所在省份=" + id;
Response.Write(sql);
this.ddlCity.DataSource = GetDataTable(sql);
this.ddlCity.DataTextField = "城市名";
this.ddlCity.DataBind();
}
//得到数据表。连接数据库
public static DataTable GetDataTable(string sql)
{
SqlConnection conn = new SqlConnection("server=.;database=wuliu;uid=sa;pwd=ddx");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);dr放置到dt数据表中
dr.Close();
return dt;
}
//绑定省份
protected void BingdingDDLProvince()
{
string sql = "select * from 省份";
this.ddlProvince.DataSource = GetDataTable(sql);
this.ddlProvince.DataTextField = "省份名"; DropDownList的数据区域
this.ddlProvince.DataValueField = "省份编号"; DropDownList的对应值
this.ddlProvince.DataBind();
}
//绑定城市
protected void BingdingDDLCity()
{
string sql = "select 城市名 from 城市表 where 所在省份='" + this.ddlProvince.SelectedValue + "'";
this.ddlCity.DataSource = GetDataTable(sql);
this.ddlCity.DataTextField = "城市名";
this.ddlCity.DataBind();
}