asp.net的dropdownlist服务器空间数据绑定
介绍asp.net的服务器空间dropdownlist的三种数据绑定:1.指向DataTable,然后绑定Text和Valu的值;2.插入一条记录,给插入的记录指定位置;3.添加一条记录;
1. 绑定datatable
DataTable
dtCategory=new DataTable();
dropdownlist.DataValueField = "ID";
dropdownlist.DataTextField =
"categoryName";
dropdownlist.DataSource =
dtCategory;
dropdownlist.DataBind();
2.插入一行
dropdownlist.Items.Insert(0, new
ListItem("请选择", "-1"));
3.添加一行
dropdownlist.Items.Add(new
ListItem(“text”,"value"));
下面是判断下拉控件是服务器控件还是表单页面控件,然后绑定数据
if (ddlDistrict is DropDownList)
{
var control = ddlDistrict as DropDownList;
control.DataSource = dt;
control.DataTextField = "DistrictName";
control.DataValueField = "DistrictID";
control.DataBind();
control.Items.Insert(0, defaultItem);
}
else if (ddlDistrict is HtmlSelect)
{
var control = ddlDistrict as HtmlSelect;
control.DataSource = dt;
control.DataTextField = "DistrictName";
control.DataValueField = "DistrictID";
control.DataBind();
control.Items.Insert(0, defaultItem);
}