问题
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