ysl-net

comboBox控件动态绑定数据

        /// <summary>
        /// load加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormAdd_Load(object sender, EventArgs e)
        {
            // 查询sql语句
            string sql = string.Format("select rankid,rankname from [rank]");
            //通过dbhelper类查询绑定comboBox控件
            comboBox1.DataSource = DBHelper.GetData(sql);
            //显示名称
            comboBox1.DisplayMember = "rankname";
            //显示id
            comboBox1.ValueMember = "rankid";

        }

 

DBHelper类里面关键代码:

/// <summary>
        /// 获取数据方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetData(string sql)
        {
            //连接数据库
            SqlConnection conn = new SqlConnection("server=.;database=DBEmployee;uid=sa;password=123456");
            conn.Open();
            //创建适配器
            SqlDataAdapter dap = new SqlDataAdapter(sql,conn);
            //创建临时数据库
            DataSet ds = new DataSet();
            //填充
            dap.Fill(ds);
            //返回数据
            return ds.Tables[0];
        }

posted on 2019-06-27 15:41 YongshiLi 阅读(...) 评论(...) 编辑 收藏

分类:

技术点:

相关文章:

  • 2021-11-07
  • 2021-04-09
  • 2021-11-28
  • 2021-11-16
  • 2021-10-31
  • 2021-12-09
  • 2021-09-19
猜你喜欢
  • 2021-08-16
  • 2021-12-29
  • 2021-04-19
  • 2021-06-26
  • 2021-07-02
  • 2021-11-03
  • 2021-05-11
相关资源
相似解决方案