繁体   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