欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

comboBox控件动态绑定数据

程序员文章站 2022-09-27 19:13:05
/// /// load加载数据 /// /// /// private void FormAdd_Load(object sender, Even ......

        /// <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];
        }