DropDownList的动态绑定方法(两种)
突然发现有两种方法可以动态绑定,都是建立在linq to entity 的基础上的
1、这个是我经常用的循环绑定
List<PassageCategory> pcategory = (from it in db.PassageCategory select it).ToList(); for (int i = 0; i < pcategory.Count; i++) { string idc = pcategory[i].PCategoryId.ToString();//绑定id string categoryc = pcategory[i].CategoryName.ToString();//绑定分类名字 category.Items.Add(new ListItem(categoryc, idc));//循环动态绑定分类 }
2、这个好像是直接通过源绑定,好像更加方便一点orz,下次可以试一试
var datascore = from it in db.PassageCategory select it; this.DropDownList.DataSource = datascore.ToList(); this.DropDownList.DataValueField = "PCategoryId"; this.DropDownList.DataTextField = "CategoryName"; this.DropDownList.DataBind(); ListItem item = new ListItem();//这里是手动新加一个项 item.Text = "全部"; item.Value = "0"; this.DropDownList.Items.Insert(0, item);