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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With