如果列表框包含,则不要添加

本文关键字:添加 列表 包含 如果 | 更新日期: 2023-09-27 18:05:48

我有一个方法:

FillListBox();

我在不同的地方调用这个方法。但有时会发生,东西被加载两次!

现在我要做的是:

if (listBox.Items[1].ToString() == "hello")
{
   DO NOT FILL
}
else
{
   FILL
}

这个不工作!(

Fault: InvalidArgument=Value of '1' is not valid for 'index'.
Parameter name: index

和类似的东西:

if(listBox.Items.Contains("hello"))
{
   DONT FILL
}

not works too:

我能做什么?

如果列表框包含,则不要添加

试试这个

if(ListBox.NoMatches != listBox.FindStringExact("StringToFind"))
  {
      listBox.Items.Add("StringToAdd");
  }

或者直接试试

 bool found = false;
 foreach (var item in listBox.Items)
 {
     if(item.ToString().Equals("StringToAdd"))
     {
         found = true;
         break;
     }
 }
if(!found)
    listBox.Items.Add("StringToAdd");

尝试:

if ( listBox.Items.Cast<ListItem>().Any(x => x.Text == "hello"))

这样做:

var item = listBox.Items.FindByValue("hello") // or FindByText
if (item != null)
{
   DONT FILL
}

您应该尝试以下内容

foreach(ListItem item in listBox)
{ 
    if(item.Value == "YourFilter")
    { 
       DONT FILL 
    }
}

如果你的项目是ASP

你应该做

foreach(object item in listBox)
{ 
    if(item == "YourFilter")
    { 
       DONT FILL 
    }
}

如果是WPF,不确定你在谈论哪个ListBox。显然,这不是最优雅的解决方案,但我认为这是合适的,如果你刚刚开始学习c#。

我解决了这个问题。我刚刚使用了myListBox.Items.Clear();

listBox.Items.Contains("hello")应该可以正常工作。

String newValue = "hello";
if (listBox1.Items.Cast<Object>().Any(x => x.ToString() == newValue))
{
    return;
}
  var findByValue = ListBox2.Items.FindByValue(rdr.GetString(0));
                        if (findByValue == null)
                        {
                            ListBox2.Items.Add(rdr.GetString(0));
                        }