[英]Items collection cannot be modified when the DataSource property is set
I get this error while trying to add items to the combobox at runtime.Is there a way to add items on runtime , even if my combobox datasource is set . 在尝试在运行时将项目添加到组合框时遇到此错误。即使设置了我的combobox数据源,也可以在运行时添加项目。
Example:My combobox has items , but i want to display "Select Category" type of statement when my form loads . 示例:我的组合框有项目,但是我想在表单加载时显示“选择类别”类型的语句。 Thanks !!!
谢谢 !!!
Assuming 假设
public class Product
{
public int Id {get;set;}
public string Name {get;set;}
}
with EF EF
var list = context.Products.Where(x = > x.Active == true).ToList();
list.Insert(0, new Product() { Id = -1, Name = "Please Select" });
selectBox.DataSource = list;
The idea is to get your database list of objects into List < Product > () first, then simply add fake item on top of that list. 这个想法是首先将对象的数据库列表放入List <Product>(),然后在该列表的顶部简单地添加假项目。
If all you want to do is display "Select Category", try this. 如果您只想显示“选择类别”,请尝试此操作。
DropDownList1.Items.Insert(0, new ListItem("Select Category"));
I'm not sure if it's possible to do this after the DataBind() but I think it should be OK. 我不确定是否可以在DataBind()之后执行此操作,但我认为应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.