Windows Form -----内容(5)
同一表格下的三级联动:
代码:
class DBconnection
{
public const string CONNECTIONSTRING = "server=.;database=mydb;uid=sa;pwd=5587725";
}
class chinastates
{
public string AreaCode { get; set; }
public string AreaName {get;set;}
public string ParentAreaCode { get; set; }
}
class chianstatesDA
{
private SqlConnection _Conn;
private SqlCommand _Cmd;
private SqlDataReader _DR;
public chianstatesDA()
{
_Conn = new SqlConnection(DBconnection.CONNECTIONSTRING);
_Cmd = _Conn.CreateCommand();
}
public List<chinastates> Select(string parentareacode)
{
List<chinastates> list = new List<chinastates>();
_Cmd.CommandText = "select * from chinastates where ParentAreaCode=@parentareacode";
_Cmd.Parameters.Clear();
_Cmd.Parameters.AddWithValue("@parentareacode",parentareacode);
try
{
_Conn.Open();
_DR = _Cmd.ExecuteReader();
while (_DR.Read())
{
chinastates data = new chinastates();
data.AreaCode = _DR["AreaCode"].ToString();
data.AreaName = _DR["AreaName"].ToString();
data.ParentAreaCode = _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 chianstatesDA().Select("0001");
//填进去
cmbProv.DataSource = list;
cmbProv.DisplayMember = "AreaName";
cmbProv.ValueMember = "AreaCode";
}
private void Fillcity()
{
string prt = (cmbProv.SelectedItem as chinastates).AreaCode;
List<chinastates> list = new chianstatesDA().Select(prt);
cmbCity.DataSource = list;
cmbCity.DisplayMember = "AreaName";
cmbCity.ValueMember = "AreaCode";
}
private void Fillcounty()
{
string prt = "";
if (cmbCity.SelectedItem!=null)
{
prt = (cmbCity.SelectedItem as chinastates).AreaCode;
}
List<chinastates> list = new chianstatesDA().Select(prt);
cmbCounty.DataSource = list;
cmbCounty.DisplayMember = "AreaName";
cmbCounty.ValueMember = "AreaCode";
}
private void Form1_Load(object sender, EventArgs e)
{
Fillprov();
Fillcity();
Fillcounty();
}
private void cmbProv_SelectedIndexChanged(object sender, EventArgs e)
{
Fillcity();
Fillcounty();
}
private void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
{
Fillcounty();
}
}