更改DataGridView颜色时,对象引用未设置为对象的实例 [英] Object reference not set to an instance of an object when changing DataGridView colors

查看:25
本文介绍了更改DataGridView颜色时,对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据行中的数据更改数据网格视图行的颜色.

I need to change the colors of a data grid view rows according to the data in the rows.

我的代码是:

foreach (DataGridViewRow Myrow in datagrid1.Rows)
{            
    if (Myrow.Cells[0].Value.Equals("Red"))
    {
        Myrow.DefaultCellStyle.BackColor = Color.Red;
    }
    {
        Myrow.DefaultCellStyle.BackColor = Color.Green;
    }
}

但是当我尝试运行它时,我得到:对象引用未设置为对象的实例

But when I try to run it I get: Object reference not set to an instance of an object

我认为是因为它一直循环遍历每一行,直到到达一行具有空值的行为止.如何阻止它这样做?

I assume it's because it keeps looping every row until it reaches some which has a null value. How do I stop it from doing that?

推荐答案

我发现我需要将DataGridView AllowUserToAddRows更改为false,并消除了底部的空行,该空行为我提供了空值.

I figured out I needed to change the DataGridView AllowUserToAddRows to false and that got rid of the empty row at the bottom which gave me the null value.

如果其他人遇到同样的情况,我将把它留在这里.

I'll leave this here if anybody else gets into the same situation.

这篇关于更改DataGridView颜色时,对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆