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();
}
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();
}
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"];
}
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.