C# ComboBox或DropDownList绑定数据的方式
往ComboBox或DropDownList添加数据,实际上可以说是大同小异,下面以ComboBox为例,具体说下都有哪些方式添加ComboBox数据列表。
一、逐条添加
//该方法可以逐条添加 comboBox2.Items.Add(项目值);
二、数组添加
string[] Array = new string[5]{'值1','值2','值3','值4','值5'};
comboBox2.Items.AddRange(Array );三、绑定数据源
//创建数据表格并赋值 DataTable dt = dataset.Tables["表格名称"]; //为了有特定的值,单独添加一行 DataRow dr = dt.NewRow(); //按列添加一行新值 dr["FirstName"] = "--选择所有--"; //插入指定的位置进数据表格 dt.Rows.InsertAt(dr, 0); //绑定数据源至comboBox comboBox1.DataSource = dt; 指定索引的列明 comboBox1.DisplayMember = "FirstName";
四、拓展方法(推荐)
这种方法使用,是为了便于后期做联动ComboBox,便于根据选择项区更改下级ComboBox值。
1、创建动态数组方法
//这里的SQL语句查询出来的数据为单列最好
string sql = "这里放添加值的数据库查询语句";
DataSet Ds_dept = Connclient.GetDataSet(sql);
DataTable DT_dept = new DataTable();
DT_dept = Ds_dept.Tables[0];
DataRow Dr_dept = DT_dept.Rows[0];
string sql_Dept_list = "这里放的是上一个SQL与的 count(*) 语句";
//获取添加数据的条数
int sql_i = Connclient.ExecSql(sql_Dept_list) + 1 ;
//定义结果集数量+1 的空数组
string[] Dept_list = new string[sql_i];
int i = 1;
//这里可以设置额外添加的值,如不需要,上面数量不+1
Dept_list[0] = "全部";
//遍历数据生成数组
foreach (DataRow row in DT_dept.Rows)
{
Dept_list[i] = row[0].ToString().Trim();
i++;
}
//这个就是要绑定的数组Dept_list2、ComboBox绑定数组
comboBox2.Items.AddRange(Dept_list);
3、联动ComboBox前置操作
//清空下拉列表值 comboBox2.Items.Clear();

