- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- string str = "data source=.;Initial Catalog=database1;uid=sa;pwd=sa;";
- SqlConnection conn = new SqlConnection(str);
- conn.Open();
- SqlCommand com = conn.CreateCommand();
- com.CommandText = "select * from promary";
- SqlDataReader da = com.ExecuteReader();
- while (da.Read())
- {
- ProvinceItem item = new ProvinceItem();
- item.Name = da.GetString(da.GetOrdinal ("proName"));
- item.id = da.GetInt32(da.GetOrdinal ("proID"));
- comboBox1.Items.Add(item.Name);
- }
- conn.Dispose();
- }
- private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
- {
- ProvinceItem item = (ProvinceItem)comboBox1.SelectedItem; //问题所在
- string str = "data source=.;Initial Catalog=database1;uid=sa;pwd=sa";
- SqlConnection conn = new SqlConnection(str);
- conn.Open();
- SqlCommand com = conn.CreateCommand();
- com.CommandText = "select * from city where proID=@id";
- com.Parameters.Add(new SqlParameter ("id",item .id));
- SqlDataReader da = com.ExecuteReader();
- while (da.Read())
- {
- ProvinceItem cityitem = new ProvinceItem();
- cityitem.Name = da.GetString(da.GetOrdinal ("cityName"));
- comboBox2.Items.Add(item.Name);
- }
- conn.Dispose();
- }
- }
- public class ProvinceItem //一个类,便于读combox的属性
- {
- public string Name { get; set; }
- public int id { get; set; }
- }
复制代码 ProvinceItem item = (ProvinceItem)comboBox1.SelectedItem;
在进行强制类型转换的时候,怎么提示出错?
|