I'm creating an application that allows the user to store information about their classes. There is a button in my application that allows the user to enter information and if it matches any item in the listBox
then it should display information about it.
I can only get it to work if I specify a particular item by position (e.g. Items[0]
) of the listBox
and then convert it to a string. My aim is to compare all items in the listBox
.
private void button3_Click(object sender, EventArgs e)
{
if (listBox2.Items[0].ToString() == "PersonalInfo")
{
label.Text = "test";
}
}
You need to loop through all of the items in the list. Try something like this:
foreach(var item in listBox2.Items)
{
if(item.ToString() == stringToMatch)
{
label.Text = "Found a match";
}
}
An alternate, simpler implementation (which will stop if/when it finds a match instead of continuing to check every item) would be
if(listBox2.Items.Any(item => item.ToString() == stringToMatch))
{
label.Text = "Found a match";
}
Write a loop to check each item
foreach(var item in listBox2.Items)
{
if (item.ToString()== "PersonalInfo")
{
label.Text = "test";
break; // we don't want to run the loop any more. let's go out
}
}
Well you could use LINQ... something like this:
if (listBox2.Items
.Cast<object>()
.Select(x => x.ToString())
.Contains("PersonalInfo"))
{
label.Text = "test";
}
Or if you want to get the details of the first match:
var match = listBox2.Items
.Cast<object>()
.FirstOrDefault(x => x.ToString() == "PersonalInfo");
if (match != null)
{
// Use match here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With