有两个 ToolStripComboBox,一个 toolStripComboBox1,一个 toolStripComboBox2,我在 toolStripComboBox1用数据库导入了机车类型type,我希望在 toolStripComboBox1选择好机车类型后,另一个 toolStripComboBox2中则出现对应的机车号码num,我写了段代码,但总是用问题,请大侠看看,怎么改实现这个功能?
     private void toolStripComboBox1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.server);
            con.Open();
            string mysql = "select  distinct type from jichexinxi";
            SqlCommand cmd = new SqlCommand(mysql, con);
            SqlDataReader dr = cmd.ExecuteReader();
            toolStripComboBox1.Items.Clear();
            while (dr.Read())
            {
                toolStripComboBox1.Items.Add(dr[0].ToString());            }
            dr.Close();
        }  private void toolStripComboBox2_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.server);
            string sql = "select num from jichexinxi where type = '" + toolStripComboBox1.SelectedItem.ToString( ) + "'";
            con.Open();
            SqlCommand cm = new SqlCommand(sql, con);
            SqlDataReader drr = cm.ExecuteReader();
            this.toolStripComboBox2.Items.Clear();
            while (drr.Read())
            {                toolStripComboBox2.Items.Add(drr[0].ToString());            }
            drr.Close();
        }

解决方案 »

  1.   

    既然你想要时间联动效果,其实查一次数据库就可以了。
    在获取机车类型的时候,将num也取出来,给两个空间绑定,不就完了
      

  2.   

    断点跟进去,看看取得Type是不是想要的,在toolStripComboBox2的Click中能够取到值吗。这样写麻烦,不如把连接数据独立出来,两个toolStripComboBox绑定。
      

  3.   

    这段代码还是能运行,但是当我先点击toolStripComboBox2时,程序就卡住了, 错误提示: string sql = "select num from jichexinxi where type = '" + toolStripComboBox1.SelectedItem.ToString( ) + "'";未将对象引用设置到对象实例
      

  4.   

    你先放到数据库里运行一下,看是否有结果,排除sql语句错误