实现省市联动需要借助ADO.NET之SQLHelper类的简单封装中的SQLHelper类,具体代码如下,主要是学习将读到的数据绑定到下拉框:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _04省市联动
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//所有的省份显示到第一个下拉框中
LoadAreaByAreaPid(0);
}
private void LoadAreaByAreaPid(int p)
{
List<Area> list = new List<Area>();
list.Add(new Area() { AreaId = -1, AreaName = "请选择" });
string sql = "select AreaId,AreaName from TblArea where AreaPId=" + p;
using (SqlDataReader reader = SqlHelper.ExecuteReader(sql))
{
if (reader.HasRows)
{
while (reader.Read())
{
Area a = new Area();
a.AreaId = Convert.ToInt32(reader["AreaId"]);
a.AreaName = reader["AreaName"].ToString();
list.Add(a);
}
}
}
cmbSheng.DataSource = list;
cmbSheng.DisplayMember = "AreaName";//主要是设置下拉框显示的值
cmbSheng.ValueMember = "AreaId";
}
private void cmbSheng_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbSheng.SelectedIndex!=0)
{
cmbCheng.Items.Clear();
//获取当前选中的省份的id
int id = Convert.ToInt32(cmbSheng.SelectedValue);
string sql = "select AreaId,AreaName from TblArea where AreaPId=" + id;
using (SqlDataReader reader = SqlHelper.ExecuteReader(sql))
{
if (reader.HasRows)
{
while (reader.Read())//练习
{
Area a = new Area();
a.AreaId = Convert.ToInt32(reader["AreaId"]);
a.AreaName = reader["AreaName"].ToString();
cmbCheng.Items.Add(a); //推荐使用上面的方法,先加入集合再将集合绑定到控件
}
}
}
}
}
}
}