//当前窗体的Load事件
private void provinceANDCity_Load(object sender, EventArgs e)
{
//连接字符串
string strConn = "Data Source=.;Initial Catalog=Province;User Id=sa;Pwd=ok";
//connection对象
SqlConnection conn = new SqlConnection(strConn);
//DataSet对象
DataSet ds = new DataSet();
//查询省份语句
string sql = "SELECT * FROM province";
SqlDataAdapter adapter = new SqlDataAdapter(sql,conn);
adapter.Fill(ds,"province");
//将省份的数据绑定到省份的下拉框中
this.cboProvince.DataSource = ds.Tables["province"];
this.cboProvince.ValueMember = "id";
this.cboProvince.DisplayMember = "provinceName"; //获取省份编号
int id = Convert.ToInt32(this.cboProvince.SelectedValue);
//根据省份编号查询城市
sql = "SELECT * FROM City WHERE proId="+id;
adapter = new SqlDataAdapter(sql,conn);
adapter.Fill(ds,"City");
//将查出来的城市绑定在城市下拉框中
this.cboCity.DataSource = ds.Tables["City"];
this.cboCity.ValueMember = "id";
this.cboCity.DisplayMember = "cityName"; //获取城市编号
int cityId = Convert.ToInt32(this.cboCity.SelectedValue);
//根据城市编号查询区县
sql = "SELECT * FROM County WHERE cityId=" + cityId;
adapter = new SqlDataAdapter(sql, conn);
adapter.Fill(ds, "County");
//将查出来的区县绑定在区县下拉框中
this.cboCounty.DataSource = ds.Tables["County"];
this.cboCounty.ValueMember = "id";
this.cboCounty.DisplayMember = "countyName"; }
//省份下拉框的事件
private void cboProvince_SelectionChangeCommitted(object sender, EventArgs e)
{
string strConn = "Data Source=.;Initial Catalog=Province;User Id=sa;Pwd=ok";
SqlConnection conn = new SqlConnection(strConn);
DataSet ds = new DataSet();
//获取省份编号
int id = Convert.ToInt32(this.cboProvince.SelectedValue);
//根据省份编号查询城市
string sql = "SELECT * FROM City WHERE proId="+id;
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
adapter.Fill(ds, "City");
//将查出来的城市绑定在城市下拉框中
this.cboCity.DataSource = ds.Tables["City"];
this.cboCity.ValueMember = "id";
this.cboCity.DisplayMember = "cityName";
}
//城市下拉框的事件
private void cboCity_SelectionChangeCommitted(object sender, EventArgs e)
{
string strConn = "Data Source=.;Initial Catalog=Province;User Id=sa;Pwd=ok";
SqlConnection conn = new SqlConnection(strConn);
DataSet ds = new DataSet(); //获取城市编号
int cityId = Convert.ToInt32(this.cboCity.SelectedValue);
//根据城市编号查询区县
string sql = "SELECT * FROM County WHERE cityId=" + cityId;
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
adapter.Fill(ds, "County");
//将查出来的区县绑定在区县下拉框中
this.cboCounty.DataSource = ds.Tables["County"];
this.cboCounty.ValueMember = "id";
this.cboCounty.DisplayMember = "countyName";
}
05-07 11:08