app.config
<configuration>
<connectionStrings>
<add name="conn" connectionString="Data Source=./SQLEXPRESS;
AttachDBFilename=D:/My Documents/Documents/Visual Studio 2010/Projects/省市查询/省市查询/省市.mdf;
Integrated Security=True;User Instance=True" />
</connectionStrings>
</configuration>
form1.cs
- using System.Text;
- using System.Windows.Forms;
- using System.Data.SqlClient;
- using System.Configuration;
- namespace 省市查询
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- string con = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
- using (SqlConnection cnn = new SqlConnection(con))
- {
- cnn.Open();
- using (SqlCommand cmd = cnn.CreateCommand())
- {
- cmd.CommandText = "select * from promary";
- using (SqlDataReader reader = cmd.ExecuteReader())
- {
- while(reader.Read())
- {
- PromaryItem items = new PromaryItem();
- items.Id = reader.GetInt32(reader.GetOrdinal("proID"));
- items.Name = reader.GetString(reader.GetOrdinal("proName"));
- cmd省.Items.Add(items);
- }
- }
- }
- }
- }
- private void cmd省_SelectedIndexChanged(object sender, EventArgs e)
- {
- cmd市.Items.Clear();
- PromaryItem items = (PromaryItem)cmd省.SelectedItem;
- int proID = items.Id;
- string con = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
- using (SqlConnection cnn = new SqlConnection(con))
- {
- cnn.Open();
- using (SqlCommand cmd = cnn.CreateCommand())
- {
- cmd.CommandText = "select * from city where proID=@proID";
- cmd.Parameters.AddWithValue("proID",proID);
- using (SqlDataReader reader = cmd.ExecuteReader())
- {
- while(reader.Read())
- {
- string cityName = reader.GetString(reader.GetOrdinal("cityName"));
- cmd市.Items.Add(cityName);
- }
- }
- }
- }
- }
- }
- class PromaryItem
- {
- public string Name{get;set;}
- public int Id{get; set; }
- }
- }