using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 三级联动.Model{ class China { private string code; public string Code { get { return code; } set { code = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string parentcode; public string Parentcode { get { return parentcode; } set { parentcode = value; } } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;namespace 三级联动.DataConnection{ class DataConnection { private static string connstr="server=.; database=mydb; user=sa; pwd=ray;"; public static SqlConnection Conn { get{ return new SqlConnection(connstr); } } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;namespace 三级联动.DataOperation{ class ChinaData { private SqlConnection _conn; private SqlCommand _cmd; private SqlDataReader _dr; public ChinaData() { _conn = DataConnection.DataConnection.Conn; _cmd = _conn.CreateCommand(); } //根据父级代号返回地区信息 public ListSelect(string pcode) { _cmd.CommandText = "select *from ChinaStates where ParentAreaCode=@pcode"; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@pcode",pcode); _conn.Open(); _dr = _cmd.ExecuteReader(); List list = new List (); if (_dr.HasRows) { while (_dr.Read()) { Model.China data = new Model.China(); data.Code = _dr[0].ToString(); data.Name = _dr[1].ToString(); data.Parentcode = _dr[2].ToString(); list.Add(data); } } _conn.Close(); return list; } }}
可视化界面操作:
后台代码:
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;namespace 三级联动{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataOperation.ChinaData cda = new DataOperation.ChinaData(); //填充省的方法 public void FillSheng() { Listlist = cda.Select("0001"); cmbSheng.DataSource = list; cmbSheng.DisplayMember = "Name"; cmbSheng.ValueMember = "Code"; } //填充市的方法 public void FillShi() { List list = cda.Select(cmbSheng.SelectedValue.ToString()); cmbShi.DataSource = list; cmbShi.DisplayMember = "Name"; cmbShi.ValueMember = "Code"; } //填充区的方法 public void FillQu() { List list = cda.Select(cmbShi.SelectedValue.ToString()); cmbQu.DataSource = list; cmbQu.DisplayMember = "Name"; cmbQu.ValueMember = "Code"; } //页面一加载运行三个方法 private void Form1_Load(object sender, EventArgs e) { FillSheng(); FillShi(); FillQu(); } //填充市的下拉列表 private void cmbSheng_SelectionChangeCommitted(object sender, EventArgs e) { FillShi(); FillQu(); } //填充区的下拉列表 private void cmbShi_SelectionChangeCommitted(object sender, EventArgs e) { FillQu(); } }}