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 阅读() 评论() 编辑 收藏

版权声明:本文为ysl-net原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/ysl-net/p/11097415.html