简体   繁体   English

将数据源分配给枚举时,如何从组合框中删除项目?

[英]How to remove an Item from a combobox when a datasource is assigned to an enum?

How to remove an Item from a combobox when a datasource is assigned to an enum? 将数据源分配给枚举时,如何从组合框中删除项目?

When trying to remove by Items.Remove , got error: 尝试通过Items.Remove删除时,收到错误消息:

Items collection cannot be modified when the DataSource property is set. 设置DataSource属性后,将无法修改项目集合。

Any suggestion? 有什么建议吗?

Note: I would keep using the enum because I deal it in many places in the code. 注意:我会继续使用该枚举,因为我在代码中的很多地方都处理过该枚举。


The code: 编码:

public enum DefaultValueType
{
    None = 0,
    Static = 1,
    Query = 2
}

cBoxDefaultType.DataSource = Enum.GetValues(typeof(DefaultValueType));

In one case, I want to remove the Query item from the options of the combobox. 在一种情况下,我想从组合框的选项中删除“查询”项。

cBoxDefaultType.Items.RemoveAt(2); // Throw exception

I found the solution by filtering the array of Enumeration: 我通过过滤Enumeration数组找到了解决方案:

Enum.GetValues(typeof(DefaultValueType))
    .Cast<DefaultValueType>()
    .Where(p => p != DefaultValueType.Query)
    .ToArray<DefaultValueType>()

You need to remove item from DataSource and rebind or use just .Items without DataSource 您需要从DataSource删除项目并重新绑定,或者只使用不带DataSource .Items

In your case you need to convert Enum to array and then work with it. 在您的情况下,您需要将Enum转换为array,然后使用它。

Also for .NET 2.0 (Remove 'Invalid' item from enum 'SomeEnum'): 同样对于.NET 2.0(从枚举“ SomeEnum”中删除“无效”项):

comboBox1.DataSource = Array.FindAll((SomeEnum[])Enum.GetValues(typeof(SomeEnum)),
(SomeEnum SM) => { return SM != SomeEnum.Invalid; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM