如何将数据源绑定到ComboBox?

时间:2013-07-18 17:03:37

标签: c# visual-studio-2012 .net-4.5 sqldatasource bindingsource

所以我目前有两个组合框。一个正在制造另一个是模型。我的SQL查询看起来像这样“从Sheet1中选择不同的模型,其中(Manufacture = @ Manufacture)”这在我执行它并且如果我要填充datagridtable时有效。但是如果我尝试将它放入组合框中,我会选择System.data.d ......等等。我怎样才能让它显示价值而不是所有这些。我做错了什么?

 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 =@Manufacture)";
        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;

            }
        }
    }

3 个答案:

答案 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;
        }

答案 1 :(得分:0)

如果您将显示成员设置为:

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

它仍然显示有趣的价值,它显示的价值是什么?

  • 请注意,在工具条中,您可能还需要执行以下操作:

    ModelComboBox.BindingContext = this.BindingContext;

here is a reference

答案 2 :(得分:0)

尝试添加

ComboBox1.ItemsSource = bindingSource3

如果这是您的答案,请将其标记为答案