comboBox控件动态绑定数据
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];
}