链接类
class DBConnection
{
public const string CONNECTIONSTRING = "server=MA-PC;database=mydb;uid=sa;pwd=111111";
}
实体类
class ChinaStates
{
public string AreaCode { get; set; }
public string AreaName { get; set ;}
public string ParetAreaCode { get; set; }
}
数据访问
class ChinaStatesDA
{
private SqlConnection _Conn;
private SqlCommand _Cmd;
private SqlDataReader _DR;
public ChinaStatesDA()
{
_Conn = new SqlConnection(DBConnection.CONNECTIONSTRING);
_Cmd = _Conn.CreateCommand();
}
public List<ChinaStates> Select(string parent)
{
List<ChinaStates> list = new List<ChinaStates>();
_Cmd.CommandText = "select *from ChinaStates where [email protected]";
_Cmd.Parameters.Clear();
_Cmd.Parameters.AddWithValue("@Parent",parent);
try
{
_Conn.Open();
_DR = _Cmd.ExecuteReader();
while (_DR.Read())
{
ChinaStates data = new ChinaStates();
data.AreaCode = _DR["AreaCode"].ToString();
data.AreaName = _DR["AreaName"].ToString();
data.ParetAreaCode = _DR["ParentAreaCode"].ToString();
list.Add(data);
}
}
finally
{
_Conn.Close();
}
return list;
}
}
按键链接
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void FillProv()
{
List<ChinaStates> list = new ChinaStatesDA().Select("0001");
cbprov.DataSource = list;
cbprov.DisplayMember = "AreaName";
cbprov.ValueMember = "AreaCode";
}
private void FillCity()
{
string parent = (cbprov.SelectedItem as ChinaStates).AreaCode;
List<ChinaStates> list = new ChinaStatesDA().Select(parent);
cbcity.DataSource = list;
cbcity.DisplayMember = "AreaName";
cbcity.ValueMember = "AreaCode";
}
private void FillCounty()
{
string parent = (cbcity.SelectedItem as ChinaStates).AreaCode;
List<ChinaStates> list = new ChinaStatesDA().Select(parent);
cbcounty.DataSource = list;
cbcounty.DisplayMember = "AreaName";
cbcounty.ValueMember = "AreaCode";
}
private void Form1_Load(object sender, EventArgs e)
{
FillProv();
//FillCity();
//FillCounty();
}
private void cbprov_SelectedIndexChanged(object sender, EventArgs e)
{
FillCity();
}
private void cbcity_SelectedIndexChanged(object sender, EventArgs e)
{
FillCounty();
}
}