简体   繁体   English

设置DataSource属性时,无法修改项目集合

[英]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.

相关问题 列表框错误:设置了DataSource属性时,无法修改项目集合 - listbox error: Items collection cannot be modified when the DataSource property is set 例外:设置DataSource属性时,无法修改项集合 - Exception : Items collection cannot be modified when the DataSource property is set 在c#中设置DataSource属性时,无法修改项目集合 - Items collection cannot be modified when the DataSource property is set in c# 设置DataSource属性时,无法修改c#项目集合 - c# Items collection cannot be modified when the DataSource property is set 如何在不同的 colors 中为列表框中的项目着色? 出现异常:设置 DataSource 属性后无法修改 Items 集合 - How to color items in listBox in different colors? getting exception : Items collection cannot be modified when the DataSource property is set 错误:其他信息:设置DataSource属性时,不能修改项目集合 - ERROR: Additional information: Items collection cannot be modified when the DataSource property is set System.ArgumentException:设置DataSource属性时,不能修改Items集合 - System.ArgumentException: Items collection cannot be modified when the DataSource property is set 设置DataSource属性后,将无法修改项目集合。 C# - Items collection cannot be modified when the DataSource property is set. c# System.ArgumentException:“设置 DataSource 属性时无法修改项目集合。” C# Windows Forms - System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.' C# Windows Forms C#ListBox:设置DataSource属性时,无法修改Items集合 - C# ListBox : Items collection cannot be modified when the DataSource property is set
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM