开发者

if ListBox Contains, don't add

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"开发者_JAVA百科)
{
   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?


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


Try:

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


Do this:

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


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#.


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


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


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));
                        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜