Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(datagridview) update a row's font color base on a column value

Tags:

c#

winforms

I'd like to ask how a row auto update its font's color base on a column's value in dataGridView.

For example, a table has 4 columns that are: id, name, rentPayMent and check.

Check for each row to see if any of the value of check == 0 If yes, then this row's font color = red Else do nothing

at the movement, i use the code as following, but it bring out error with

Object reference not set to an instance of an object,System.NullReferenceException was unhandled

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells[3].Value.ToString() == "0") //**Object reference not set to an instance of an object**
        {
            row.DefaultCellStyle.BackColor = Color.Red;  //then change row color to red
        }
    }
}

Thanks for all, i got the solution already.

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (dataGridView1.Rows[e.RowIndex].Cells[3].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString()))
        {
            if (dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString().Trim() == "0")
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            dataGridView1.Rows[e.RowIndex].Cells[3].Style = dataGridView1.DefaultCellStyle;
        }

    }
like image 498
Kam2012 Avatar asked Nov 24 '22 08:11

Kam2012


1 Answers

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
    {
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = new DataGridViewCellStyle { ForeColor = Color.Orange, BackColor = Color.Blue };
    }
    else
    {
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = dataGridView1.DefaultCellStyle;
    }
}
like image 96
Jignesh.Raj Avatar answered Feb 23 '23 00:02

Jignesh.Raj