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.Configuration;
using System.Data.SqlClient;
namespace 省市选择
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//程序加载时,向省中填充数据
private void Form1_Load(object sender, EventArgs e)
{
//读取数据库连接字符串
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
//创建数据库连接
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//查询出promary中所有的记录
cmd.CommandText = "select * from promary";
//返回一个dataReader
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
//循环读取每条dataReader记录
while(dataReader.Read())
{
//创建一个item类
ProvinceItem item = new ProvinceItem();
//类item.Id=数据库中省的编号
item.Id = dataReader.GetInt32(dataReader.GetOrdinal("proid"));
//类item.Name=数据库中省的名称
item.Name = dataReader.GetString(dataReader.GetOrdinal("proname"));
//填充item到cmb省中,并设置DispalyMember为item的Name属性则cmb省会显示省的名称
cmb省.Items.Add(item);
}
}
}
}
}
//省选择发现变化时响应的事件
private void cmb省_SelectedIndexChanged(object sender, EventArgs e)
{
cmb市.Items.Clear();
//创建item类指向=cmb省的item
ProvinceItem item = (ProvinceItem)cmb省.SelectedItem;
//获得省的编号
int proId = item.Id;
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from city where proID=@proID";
cmd.Parameters.Add(new SqlParameter("proID", proId));
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
string cityName = dataReader.GetString(dataReader.GetOrdinal("cityName"));
cmb市.Items.Add(cityName);
}
}
}
}
}
}
class ProvinceItem
{
public string Name { get; set; }
public int Id { get; set; }
}
}