我想问一行如何根据dataGridView
.
例如,一个表有 4 列,它们是:id, name, rentPayMent and check
.
检查每一行是否有任何值check == 0
If yes, then this row's font color = red
Elsedo nothing
在运动中,我使用以下代码,但它会导致错误
对象引用未设置为对象的实例,System.NullReferenceException 未处理
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
}
}
}
谢谢大家,我已经得到了解决方案。
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;
}
}