簡體   English   中英

使用SQLDataReader從數據庫向ComboBox添加項目

[英]Add items to ComboBox from Database using SQLDataReader

我正在嘗試從數據庫向Windows窗體ComboBox添加項目,以下代碼對我有用。 代碼中引用的表Course有2列,CourseId和CourseName,我想將顯示成員設置為CourseName,將值成員設置為CourseId。

請告訴我我需要在以下代碼中進行哪些其他更改才能實現此目的?

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

嘗試這個..!

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

使用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"];
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM