Search code examples
c#visual-studio-2012.net-4.5sqldatasourcebindingsource

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;

            }
        }
    }

Solution

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