Click here to Skip to main content
16,004,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,
I am trying to change the cell color. The code run successfully and the Back color changes but after sometime i get error which is Object reference not set to an instance of an object. at line

if (theRow.Cells[colIndex].Value.ToString() == "Normal")




C#
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            int colIndex = e.ColumnIndex;
            int rowIndex = e.RowIndex;

if ( ! theRow.Cells[colIndex].Value.Equals(Null))
{
            if (rowIndex >= 0 && colIndex >= 0)
            {
                DataGridViewRow theRow = dataGridView1.Rows[rowIndex];


                if (theRow.Cells[colIndex].Value.ToString() == "Normal")
                {
                    theRow.DefaultCellStyle.BackColor = Color.Green;
                }


                else if (theRow.Cells[colIndex].Value.ToString() == "Critical")
                {
                    theRow.DefaultCellStyle.BackColor = Color.Red;

                }
}
Posted
Updated 11-Mar-13 21:52pm
v2
Comments
Zoltán Zörgő 11-Mar-13 4:51am    
Ant what is in the theRow.Cells[colIndex] at that point? Debug and see.

theRow.Cells[colIndex].Value appears to have become null for this particular scenario.
When you try to convert null to a string using toString, you will get this error.

Check why you are getting null in this value.
If null is unavoidable, check for null before converting to string or use Convert.ToString().
 
Share this answer
 
reason is
you are getting...
theRow.Cells[colIndex].Value is NULL and you are tring to use tostring conversion method
Null.ToString()

that is error because NULL haven't a method tostring()

so,...
C#
if ( ! theRow.Cells[colIndex].Value.Equals(Null))
{
    if (theRow.Cells[colIndex].Value.ToString() == "Normal")
    {
        ...
    }
}

Happy Coding!
:)
 
Share this answer
 
Comments
ontheline89 12-Mar-13 3:51am    
Still i am getting same error.
Aarti Meswania 12-Mar-13 3:54am    
check you have colindex in grid
means if you give 3 in colindex and grid have 3 columns then it will cause error
because col count begin from 0,1,2 = total 3 column now if search for colindex = 3 then nu such col in grid
ontheline89 12-Mar-13 3:57am    
Thank you for your quick reply, I have 4 columns in my Grid.
Aarti Meswania 12-Mar-13 3:59am    
then debug & check value of colindex it should not be greater then 3
ontheline89 12-Mar-13 4:00am    
ok thank you. I will check now.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900