http://www.programfan.com/blog/article.asp?id=28128
代码如下:
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.Data.SqlClient;
namespace Test_PromaryCity
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=Database1.mdf;Integrated Security=True;Pooling=False"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select * from promary";
using (SqlDataReader dataRead = cmd.ExecuteReader())
{
while (dataRead.Read())
{
promaryItem Item = new promaryItem(); //注意此处不能写在using 外面
Item.id = dataRead.GetInt32( dataRead.GetOrdinal("proID"));
Item.name = dataRead.GetString( dataRead.GetOrdinal("proName"));
cmb_promary.Items.Add(Item);
}
}
}
}
}
private void cmb_promary_SelectedIndexChanged(object sender, EventArgs e)
{
promaryItem Item =(promaryItem)cmb_promary.SelectedItem;
int proId = Item.id;
cmb_city.Items.Clear();//clear the previous data
using (SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=Database1.mdf;Integrated Security=True;Pooling=False"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//string sqlStr = @"Select * from city where proId = " + proId;
//cmd.CommandText = sqlStr;
//equals the under statement
cmd.CommandText = "Select * from city where proId = @proId";
cmd.Parameters.Add(new SqlParameter("proId", proId));
using (SqlDataReader dataRead = cmd.ExecuteReader())
{
while (dataRead.Read())
{
string cityName = dataRead.GetString( dataRead.GetOrdinal( "cityName") ); //read DataBase data
cmb_city.Items.Add(cityName);
}
}
}
}
}
}
class promaryItem
{
public string name{get;set;}
public int id{ get;set;}
}
}
http://www.programfan.com/blog/article.asp?id=28128