anesthetic
anesthetic

Reputation: 203

How to change datagridview row color based on string value

I've tried searching the forums to find the answer, but they all seem to check for an integer value, not a string. I've got a C# form pulling data values from an SQL table and displaying them on a datagridview. The column I wish check the string value for is labeled "Type", and is the third column in my data table. I wish to highlight all rows red that contain 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 conduct actions that should trigger the databindingcomplete event. Frustratingly, if I change row.Cells[2] to row.Cells[3] where I have integer values, and type

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

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

Edit: Yes, sorry, I should have been consistent. The value I wish to compare to is "Pharmacy", capitalized.

Edit2: Ok I found out why it was giving me so much trouble. The values in column[2] were being added in by a combobox, and for some reason it always adds two spaces after the word even though it does not show the spaces in the string collection editor.

Upvotes: 4

Views: 4847

Answers (1)

Fabio
Fabio

Reputation: 32453

Because your code works with column of integers, then problem must be in the string comparing.
As I mentioned in the comments check what data you have and value comparing to.
Or you can execute ToLower() on the cell value and compare it to "pharmacy"
And you can use CellFormatting event handler. This event should be good for formatting control based on the values

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;
    }
}

Upvotes: 2

Related Questions