How to change datagridview row color based on string value

I tried searching the forums to find the answer, but they all seem to be checking an integer value, not a string. I have a C # form retrieving data values ​​from a SQL table and displaying them on a datagridview. The column I need is validating a string value, designated as "Type", and is the third column in my data table. I want to highlight all red lines containing the word "pharmacy" in the third column.

private void invTableDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow row in invTableDataGridView.Rows)
        {
            if (row.Cells[2].Value.ToString() == "Pharmacy")
            {
                invTableDataGridView.DefaultCellStyle.BackColor = Color.Red;
            }
        }

    }

      

When I run the program with this code, nothing changes, even when I perform actions that should fire a data binding event. Disappointing if I change row.Cells [2] to row.Cells [3] where I have integer values ​​and enter

    if (row.Cells[3].Value.ToString() == "0")

      

the code works, but for the wrong column. It seems to only work with integers, but I want it to work with a string. How to do it?

Edit: Yes, sorry, I had to be consistent. The value I want to compare is "Pharmacy" capitalized.

Edit2: Ok, I found out why this bothered me so much. The values ​​in column [2] were added with a combobox and for some reason it always adds two spaces after the word even though it doesn't display spaces in the string collection editor.

+3


source to share


1 answer


Since your code is working on a column of integers, then the problem must be with the string comparison.
As I mentioned in the comments, check what data you have and the value versus.
Or you can step ToLower()

on the cell value and compare it to "pharmacy"
AND you can use an event handler CellFormatting

. This event should be good for value-based formatting control



private void invTableDataGridView_CellFormatting(Object sender,
                                                 DataGridViewCellFormattingEventArgs e)
{
    Int32 yourindexColumn = 2;
    if (e.RowIndex < 0 || e.ColumnIndex <> yourindexColumn)
        Return;
    //Compare value and change color
    DataGridViewCell cell = invTableDataGridView.Rows[e.RowIndex].Cells[yourindexColumn]
    String value = cell.Value == null ? string.Empty : cell.Value.ToString()
    if (value.ToLower().Equals("pharmacy") == true)
    {
        invTableDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    }
}

      

+2


source







All Articles