Edwin Torres
Edwin Torres

Reputation: 483

C#: if else statement with listView

what i am trying to do is check if the listView (column5) contains ANY items with the word 'Yes'. If it does write 'Great', if the column does not contain any items at ALL with the word 'Yes' write 'Bad'.

Whats happening now is my program is only writing Bad (the else statement) even if the column does contain an item that has the word 'Yes'.

How can I fix this?:

foreach (ListViewItem item in listView1.Items) {
    if (item.SubItems[5].Text.Contains("Yes")) {
        // Do your work here
        labelContainsVideo2.Text = "GREAT";
        labelContainsVideo2.ForeColor = System.Drawing.Color.Green;
    } else {
        labelContainsVideo2.Text = "BAD";
        labelContainsVideo2.ForeColor = System.Drawing.Color.Red;
    }
}

Upvotes: 1

Views: 1278

Answers (3)

Evgeny Lukashevich
Evgeny Lukashevich

Reputation: 1517

Try this:

if(listView1.Items.Cast<ListViewItem>().Any(i => i.SubItems[5].Text.ToLower().Contains("yes"))){
    labelContainsVideo2.Text = "GREAT";
    labelContainsVideo2.ForeColor = System.Drawing.Color.Green;
}
else
{
    labelContainsVideo2.Text = "BAD";
    labelContainsVideo2.ForeColor = System.Drawing.Color.Red;
}

Upvotes: 1

Diego
Diego

Reputation: 16714

Maybe for the case?

foreach (ListViewItem item in listView1.Items)
{
  if (item.SubItems[5].Text.ToUpper().Contains("YES"))
  {
    // Do your work here
    labelContainsVideo2.Text = "GREAT";
    labelContainsVideo2.ForeColor = System.Drawing.Color.Green;
  }
  else
  {
    labelContainsVideo2.Text = "BAD";
    labelContainsVideo2.ForeColor = System.Drawing.Color.Red;
  }
}

Also, have in mind that this way it will only count the last item. If you want to show all items state you should have a labels array or something. If what you want is to know if any items contains 'Yes', you should follow @ZombieSheep answer.

Upvotes: 2

ZombieSheep
ZombieSheep

Reputation: 29953

If the last item in your list doesn't contain "Yes", then the output will be "BAD", regardless of what the other items contain.

Try this instead...

string message = "BAD";
var msgColor = System.Drawing.Color.Red;
foreach (ListViewItem item in listView1.Items)
{
    if (item.SubItems[5].Text.Contains("Yes"))
    {
        message = "GREAT";
        msgColor = System.Drawing.Color.Green;
        break;   // no need to check any more items - we have a match!
    }
}
labelContainsVideo2.Text = message ;
labelContainsVideo2.ForeColor = msgColor;

Upvotes: 1

Related Questions