1.运用ComboBox的控件建立效果,如右图:
2.建立三个表,第一个Province表: PID,PName;第二个为city表: CId,CName,PId;第三个为coun表:CounID,CounName,CId;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 三级联动
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BindProvince()
{
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=三级联动;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select PID, PName from prov", conn);
DataTable dt = new DataTable();
da.Fill(dt);
//for (int i = 0; i < dt.Rows.Count; i++)
//{
// this.comboBox1.Items.Add(dt.Rows[i]["PName"].ToString());
//}
this.comboBox1.DataSource = dt;
this.comboBox1.DisplayMember = "PName";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > -1)
{
DataRowView drv = (DataRowView)comboBox1.SelectedItem;
string pId = drv.Row["PID"].ToString();
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=三级联动;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select CId, CName from City where PId='" + pId + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds,"City");
DataTable dtUser = ds.Tables["City"];
comboBox2.DataSource = dtUser;
comboBox2.DisplayMember = "CName";
comboBox2.ValueMember = "CID"