【发布时间】:2013-01-03 04:15:34
【问题描述】:
我想问一行如何根据dataGridView 中列的值自动更新其字体颜色。
例如,一个表有 4 列,它们是:id, name, rentPayMent and check。
检查每一行是否有check == 0 的值
如果是,则此行的字体color = red 否则为do 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;
}
}
【问题讨论】:
-
我认为您应该引用此链接我会帮助您 [staskoverflow][1] [1]:stackoverflow.com/questions/12202751/…