Object reference not set to an instance of an object when changing DataGridView colors

泄露秘密 提交于 2020-01-25 21:06:09

问题


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

My code is:

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?


回答1:


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.



来源:https://stackoverflow.com/questions/39657748/object-reference-not-set-to-an-instance-of-an-object-when-changing-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!