2013-07-18 147 views
0

所以我目前有两个组合框。一个正在制造另一个正在成型。我的SQL查询看起来像这样“选择不同的模型从sheet1其中(制造= @制造)”这工作时,我执行它,如果我要填充datagridtable。但是如果我尝试将它放入组合框中,我会为我的选择获取System.data.d ......等。我怎么才能让它显示值而不是所有这些。我究竟做错了什么?如何将数据源绑定到ComboBox?

private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     string manu = comboBox3.Text; 
     string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True"; 
     string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture [email protected])"; 
     using (SqlConnection conn = new SqlConnection(conStr)) 
     { 

      SqlCommand cmd = new SqlCommand(sqlcmd, conn); 

      cmd.Parameters.AddWithValue("@Manufacture", manu); 

      SqlDataReader dr = cmd.ExecuteReader(); 
      if (dr.HasRows) 
      { 
       dr.Close(); 
       SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); 
       SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);      
       DataTable table = new DataTable(); 
       table.Locale = System.Globalization.CultureInfo.InvariantCulture; 
       dataAdapter.Fill(table); 
       bindingSource3.DataSource = table;     
       ModelComboBox.DataSource = bindingSource3; 

      } 
     } 
    } 
+0

你试过设置['DisplayMember'(http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember.aspx)? – Sayse

+0

我没有。将尝试。 –

+0

我没有运气。你会如何推荐我的方法? –

回答

2

你可以给这个试试吗?

 using (SqlConnection conn = new SqlConnection(conStr)) 
     { 
      conn.Open(); 
      SqlCommand cmd = new SqlCommand(sqlcmd, conn); 

      cmd.Parameters.AddWithValue("@Manufacture", manu); 

      SqlDataReader dr = cmd.ExecuteReader(); 

      IList<string> modelList = new List<string>() 
      while (dr.Read()) 
      { 
       modelList.add(dr[0].ToString()); 
      } 

      ModelComboBox.DataSource = modelList; 
     } 
+0

另外我注意到变量“manu”没有分配到任何地方 – sean717

+0

去试试这个出来现在 –

+0

工作!你达人老大!今天学到了新东西谢谢你:) –

0

如果你已经设置了显示部件,如:

ModelComboBox.DataSource = bindingSource3; 
ModelComboBox.DisplayMember = "ColumnName"; 

它仍然显示了有趣的价值观,什么是它准确显示值是多少?

  • 注意,在工具条,它看起来像你可能也必须做到:

    ModelComboBox.BindingContext = this.BindingContext;

here is a reference

0

尝试增加

ComboBox1.ItemsSource = bindingSource3 

如果是那么你的回答将其标记为答案