ListBox重复检查

问题描述 投票:0回答:2

我昨天发布了another question,但我没有进一步的回复,因为有两个答案。不幸的是,它们都不适合我。如果这违反了重新发布类似问题的规则,请道歉。

我正在尝试按下按钮时检查ListBox是否有重复项。应该将ComboBox的值添加到ListBox

使用Linq查询建议的所有答案都是这样的

myListBox.Items.Any(item=>((EnquiryListItem)item).Text == ComboBox1.SelectedText.ToString())

或这个

if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){

但是,我的控件没有AnyCast的条目。

我尝试使用foreach循环,如下所示,但我得到一个错误,object does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'object' could be found

            foreach (var item in ListBox1.Items)
            {
               if (item.Text.Contains(Combobox1.SelectedText.ToString()))
               {
                   //select item in the ListBox
                   debugMsg("Duplicate","");
                   break;
               } else {
                ListBox1.Items.Add(Combobox1.SelectedItem); }
            }

我还可以使用其他任何方法吗?我一直搜索SO和互联网,但每次都会遇到相同的建议 - 几乎总是使用Linq,这显然不适用于我的供应商特定的SDK Windows窗体应用程序。他们记录了他们的ListBox控件,并建议它继承.NET控件,但只提供添加/删除项目的代码,没有重复检查。

c# listbox
2个回答
1
投票

确保你使用System.Linq,因为Cast应该工作。 我使用以下代码完成了您想要的结果:

if ( listBox1.Items.Cast<string>().Contains( comboBox1.SelectedItem.ToString() ) )
{
    MessageBox.Show( "duplicate" );
}
else
{
    listBox1.Items.Add( comboBox1.SelectedItem );
}

自定义控件(OP的情况): 如果foreach解决方案适用于您的自定义控件并且.Text不是有效的扩展方法,则只需使用:

item.ToString().Contains(Combobox1.SelectedItem.ToString())

0
投票

如EpicKip所建议的,使用没有Text的foreach循环

            if ( ListBox1.Items.Contains( ComboBox1.SelectedItem ) )
            {
                debugMsg( "duplicate", "" );
            }
            else
            {
                ListBox1.Items.Add( ComboBox1.SelectedItem );
            }
© www.soinside.com 2019 - 2024. All rights reserved.