您的位置:首页 > 数据库

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

2018-03-06 14:36 756 查看
下拉框动态加载数据库某字典表里的字段作为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");
        }
效果截图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: