简体   繁体   中英

How do i bind data source to a ComboBox?

So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =@Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?

 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;

            }
        }
    }

Can you give this a try?

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

If you have set the display member like:

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

And it still shows funny values, what are the values that it shows exactly?

  • Note, in a toolstrip it looks like you may have to also do:

    ModelComboBox.BindingContext = this.BindingContext;

here is a reference

Try adding

ComboBox1.ItemsSource = bindingSource3

if this is your answer then mark it as answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM