C#下拉框ComboBox动态绑定数据库源

下拉框动态加载数据库某字典表里的字段作为item展示。

思路是:
1数据库访问辅助类 SQLhelper;   用途:把从数据库表中查询到字段加载到datatable里面备用;
2一个combox辅助类 SetComboData用途:把datatable里的各个row加载到combox的item里
3最后在包含Combobox的界面
实现:
1先准备出来 SQLhelper
internal class SQLhelper
    {
        public static SqlConnection conn;
        //打开数据库连接
        private static void OpenConn(string connectionString)
        {
            conn = new SqlConnection(connectionString);
            if (conn.State.ToString().ToLower() != "open")
            {
                conn.Open();
            }
        }
        //关闭数据库连接
        public static void CloneConn()
        {
            if (conn.State.ToString().ToLower() != "open")
            {
                conn.Close();
                conn.Dispose();
            }
        }
        // DataTable
        public DataTable GetDataTableValue(string connectionString, string sql)
        {
            OpenConn(connectionString);
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, conn);
            DataTable dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            CloneConn();
            return dataTable;
        }
    }
}

2准备

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace MedicalRecord.Class
{
    internal class SetCommData
    {
        private CheckConfig checkConfig = new CheckConfig();
        private SQLhelper sqLhelper = new SQLhelper();
     
      public void SetCommItem(ComboBox comboBox, string tablename)
        {
            List<string> contenList = new List<string>();
            string connectionstr = checkConfig.GetAppSettings();
            //sql大家要根据实际情况,可能SetCommItem整个方法都要重新改造
            string sqlstr = string.Format("select name from {0}  where name <>'' and name is not null ", tablename);
            DataTable dt = sqLhelper.GetDataTableValue(connectionstr, sqlstr);
            //加载到combobox
            comboBox.Items.Clear();
            comboBox.Items.Add("");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                comboBox.Items.Add(dt.Rows[i]["name"]);
            }
            comboBox.SelectedText = "";
        }
    }
}

3调用:

  private void LoadCommonData()
        {
            setCommData.SetCommItem(xb, "mis.dbo.DICT_ADMISSION");
            setCommData.SetCommItem(ryks, "mis.dbo.DICT_ADMISSION");
        }
效果截图:

猜你喜欢

转载自blog.csdn.net/u013667895/article/details/79457438