【问题标题】:Add items to ComboBox from Database using SQLDataReader使用 SQLDataReader 将项目从数据库添加到 ComboBox
【发布时间】:2014-03-19 16:50:25
【问题描述】:

我正在尝试将项目从数据库添加到 Windows 窗体组合框,以下代码对我有用。代码中引用的表 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();
}

【问题讨论】:

    标签: .net c#-4.0 sqldatareader


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      试试这个..!

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

      【讨论】:

      • 我正在使用 Windows 窗体,并且 ComboBox 控件没有 DataBind() 方法。请告诉我任何替代方案。
      • 尝试不使用DataBind() 然后
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2012-11-12
      • 2015-10-09
      • 1970-01-01
      相关资源
      最近更新 更多