if ListBox Contains, don't add

假如想象 提交于 2019-12-10 18:19:21

问题


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?


回答1:


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");



回答2:


Try:

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



回答3:


Do this:

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



回答4:


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:


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




回答6:


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




回答7:


String newValue = "hello";
if (listBox1.Items.Cast<Object>().Any(x => x.ToString() == newValue))
{
    return;
}


来源:https://stackoverflow.com/questions/7077741/if-listbox-contains-dont-add

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!