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 省市的选择
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source =.\SQLEXPRESS;AttachDBFilename = |DataDirectory|\Database1.mdf;Integrated Security= true ;User Instance=true")) //该处用 using()的目的是释放内存,以下也一样
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from promary";
using (SqlDataReader reader = cmd.ExecuteReader())
{
//Readpromary items = new Readpromary();//在该处声明读取到的proID时最后一个字段(在本数据库中时35)
while (reader.Read())
{
Readpromary items = new Readpromary();
items.Id = reader.GetInt32(reader.GetOrdinal ("proID"));
items.Name = reader.GetString(reader.GetOrdinal ("proName"));
cmb_sheng.Items.Add(items);
}
}
}
}
}
private void cmb_sheng_SelectedIndexChanged_1(object sender, EventArgs e)
{
Readpromary items = (Readpromary)cmb_sheng.SelectedItem;//指针只认变量类型不认实际对象,所以要进行类型转换
int proID = items.Id;
using (SqlConnection conn = new SqlConnection(@"Data Source =.\SQLEXPRESS;AttachDBFilename = |DataDirectory|\Database1.mdf;Integrated Security= true ;User Instance=true")) //该处用 using()的目的是释放内存,以下也一样
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from city where proID = @ProID";
cmd.Parameters.Add(new SqlParameter("ProID", proID));
using (SqlDataReader reader = cmd.ExecuteReader())
{
//Readpromary cityItem = new Readpromary();
while (reader.Read())
{
// cityItem.Name = reader.GetString(reader .GetOrdinal ("cityName"));
string cityName = reader.GetString(reader.GetOrdinal("cityName"));
cmb_shi.Items.Clear(); //清除上一次添加的痕迹
cmb_shi.Items.Add(cityName);
}
}
}
}
}
}
class Readpromary
{
public string Name { get; set; }
public int Id { get; set; }
}
}
代码改进后,在cmb_shi中只有一个可选项,具体如图:
|