我想问一个行如何自动更新其字体颜色基于dataGridView
的列值。(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;
}
}
我想你应该Refar此链接我要帮助你 [staskoverflow] [1] [1]: http://stackoverflow.com/questions/12202751/how-can-i-make-a-datagridview-cells-font-a-particular-color –
winforms或asp.net? –
它是在winforms中。 – Kam2012