if ListBox Contains, don't add

2019-07-13 02:52发布

I've got a Method:

FillListBox();

I call this method from different places.. But sometimes it happens, that things were loaded twice!

Now I'm trying to do something like:

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

THIS DONT WORKS! :(

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

And something like that:

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

Dont works too :(

What can I do?

标签: c# listbox
7条回答
对你真心纯属浪费
2楼-- · 2019-07-13 03:18

Try:

if ( listBox.Items.Cast<ListItem>().Any(x => x.Text == "hello"))
查看更多
男人必须洒脱
3楼-- · 2019-07-13 03:18

Do this:

var item = listBox.Items.FindByValue("hello") // or FindByText
if (item != null)
{
   DONT FILL
}
查看更多
何必那么认真
4楼-- · 2019-07-13 03:20

You should try something along the lines of

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

if your project is ASP

you should do

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

if it's WPF, not sure which ListBox you're talking about. Obviously this isn't the most elegant solution, but I suppose it's appropriate if you're just starting to learn C#.

查看更多
看我几分像从前
5楼-- · 2019-07-13 03:23

listBox.Items.Contains("hello") should work fine.

查看更多
We Are One
6楼-- · 2019-07-13 03:24

Try this

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

or simply try this

 bool found = false;

 foreach (var item in listBox.Items)
 {
     if(item.ToString().Equals("StringToAdd"))
     {
         found = true;
         break;
     }
 }
if(!found)
    listBox.Items.Add("StringToAdd");
查看更多
我命由我不由天
7楼-- · 2019-07-13 03:25

I solved the problem.. I just used myListBox.Items.Clear();

查看更多
登录 后发表回答