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];
}
下一篇: 那是你以为
推荐阅读