Question

I'm trying to add items to a Windows Forms ComboBox from database and the following code is working for me. The table Course referenced in the code has 2 columns, CourseId and CourseName and I want to set display member to CourseName and value member to CourseId.

Please tell me what additional change I need to do in the following code to make that happen?

private void LoadCourse()
{
        SqlConnection conn = new SqlConnection(sasdbConnectionString);
        SqlCommand cmd = new SqlCommand("SELECT CourseId FROM Courses", conn);

        cmd.CommandType = CommandType.Text;

        conn.Open();

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            this.courseComboBox.Items.Add(dr.GetInt32(0));
        }

        dr.Close();

        conn.Close();
}
Was it helpful?

Solution

Try this with sql adapter

private void LoadCourse()
 {
    SqlConnection conn = new SqlConnection(sasdbConnectionString);
    string query = "SELECT CourseId,CourseName FROM Courses";
    SqlDataAdapter da = new SqlDataAdapter(query, conn);
    conn.Open();
    DataSet ds = new DataSet();
    da.Fill(ds, "Course");
    courseComboBox.DisplayMember =  "CourseName";
    courseComboBox.ValueMember = "CourseId";
    courseComboBox.DataSource = ds.Tables["Course"];
 }

OTHER TIPS

Try This..!

private void LoadCourse()
{
    SqlConnection conn = new SqlConnection(sasdbConnectionString);
    SqlCommand cmd = new SqlCommand("SELECT CourseId,CourseName FROM Courses", conn);

    cmd.CommandType = CommandType.Text;

    conn.Open();

    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        this.courseComboBox.DisplayMember =dr[0];
        this.courseComboBox.ValueMember = dr[1];
        this.courseComboBox.DataSource = dr;

    dr.Close();

    conn.Close();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top