Home > front end >  Datagridview compare cell string
Datagridview compare cell string

Time:02-01

I need to compare 2 String-Values in one cell.(if in cell 1 is a string like 'DPS' and 'MAN') But I dont know why my && Operator does not work like i think. I dont get an Result.

enter image description here

Can someone explain what I am doing wrong here?

private void Warning()
{
    foreach (DataGridViewRow row in dataGridView4.Rows)
        if (row.Cells[1].Value.ToString() == "DPS" 
            && row.Cells[1].Value.ToString() == "MAN")
        {
            panelWarnung.BackColor = Color.Red;
        }
        else
        {
            panelWarning.BackColor = Color.LightGreen;
        }
}

SOLUTION

This works!

foreach (DataGridViewRow row in dataGridView4.Rows)
            if (row.Cells[1].Value.ToString().Contains("DPS") == row.Cells[1].Value.ToString().Contains("MAN"))
                panelWarning.BackColor = Color.Red;

CodePudding user response:

if DPS and MAN is in the cell the warningPanel should turn red

That's

row.Cells[1].Value.ToString().Contains("DPS") 
    && row.Cells[1].Value.ToString().Contains("MAN")

Contains tests whether the string is present somewhere within the cell. == tests whether the entire whole string in the cell is exactly equal to some value.. And no variable can be simultaneously equal to two different values

Contains will permit you to have cell values like:

MANDPS
DPS,MAN
DPSINGH'S MANAGER

:)

CodePudding user response:

I may be wrong, but it seems to me that what you want is not and, but or. Or in other words, || instead of &&:

if (row.Cells[1].Value.ToString() == "DPS" 
        || row.Cells[1].Value.ToString() == "MAN") {
    panelWarnung.BackColor = Color.Red;
    break; // <-- NB!!
}

Now your panel should be set to the specified color if either DPS or MAN is contained in one of the cells.

NOTE however that you'll also need to add the break statement after setting the color to red, otherwise you risk it being overridden and set to gree for the next correct row.

  •  Tags:  
  • Related