从组合框列表中删除重复项 [英] remove duplicate from combo box list

查看:130
本文介绍了从组合框列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用数据库中的数据填充了组合框,我想从组合框项目列表中删除重复的名称。你能给我一个代码吗?

I have populated the combo box with data from a database and I wanted to remove the duplicate names from the combo box items list. Can you give me a code to do it?

推荐答案

它不一定那么简单 - 它取决于你填充ComboBox的项目类型用。因为你不能只设置Items数组(它不公开公共setter,只是getter)你必须创建一个新的项目数组,删除重复项,然后将它设置回ComboBox:



It's not necessarily as simple as that - it depends to an extent on what type of items you have filled your ComboBox with. Because you can't just set the Items array (it exposes no public setter, just the getter) you have to create a new array of items, remove the duplicates, and set it back into the ComboBox:

List<object> list = new List<object>();
foreach (object o in myComboBox.Items)
    {
    if (!list.Contains(o))
        {
        list.Add(o);
        }
    }
myComboBox.Items.Clear();
myComboBox.Items.AddRange(list.ToArray());


为什么不从数据库本身获取唯一的?

喜欢:

Why not just fetch the unique ones from database itself?
Like:
SELECT DISTINCT Names FROM MstNames





如果您仍然希望在分配数据源之前过滤要使用的数据表。

要了解更多信息,请阅读: MSDN :DataView.RowFilter属性 [ ^ ]


由于Sandeep的答案最佳方式是从数据库中选择时选择不同。



如果你使用c#3.0或更高版本你可以尝试下面的代码



As Sandeep's answer best way is select distinct when you select from database.

if you are using c# 3.0 or later you can try below code

var itemArry= myComboBox.Items.SelectMany(i => i).Distinct().ToArray();
myComboBox.Items.Clear();
myComboBox.Items.AddRange(itemArry);


这篇关于从组合框列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆