2014-03-19 138 views
0

我想從數據庫添加項目到Windows窗體組合框,下面的代碼正在爲我工​​作。代碼中引用的表格有2列,CourseId和CourseName,我想將顯示成員設置爲CourseName,並將值成員設置爲CourseId。使用SQLDataReader將項目從數據庫添加到組合框

請告訴我在下面的代碼中需要做什麼額外的更改才能實現?

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

回答

0

與SQL適配器

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"]; 
} 
+0

感謝哥們,它的工作! –

0

試試這個..!

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(); 
} 
+0

我使用Windows Forms和存在的ComboBox控件的DataBind沒有()方法試試這個。請告訴我任何替代方案。 –

+0

嘗試不用'DataBind()'然後 – Jegadeesh