如何将数据源绑定到组合框

本文关键字:组合 绑定 数据源 | 更新日期: 2023-09-27 18:23:45

所以我目前有两个组合框。一个是制造,另一个是模型。我的sql查询看起来像这样"从sheet1中选择不同的模型,其中(Manufacture=@Manufacture)",当我执行它时,如果我要填充数据网格表,它就会起作用。但是,如果我试图把它放在一个组合框中,我会得到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;
            }
        }
    }

如何将数据源绑定到组合框

你能试试吗?

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

如果您设置了显示成员,如:

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

它仍然展示了有趣的价值观,它到底展示了什么价值观?

  • 注意,在工具之旅中,您可能还必须执行以下操作:

    ModelComboBox.BindingContext=此。BindingContext;

这是一个参考

尝试添加

ComboBox1.ItemsSource = bindingSource3

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