-1

i m looping through table to find out cell have csstdgreen. i give an error Object reference not set to an instance of an object.

 for(int i = 0; i < mytable.Rows.Count; i++)
            {
                for(int j = 0; j < mytable.Rows[i].Cells.Count; j++)
                {
                    if(mytable.Rows[i].Cells[j].Attributes["class"].Equals("csstdgreen"))
                    {

                    }
                }
            }
<table id="mytable" runat="server">
<tr class="csstablelisttd">
            <td>
                09:00AM
            </td>
            <td class="csstdgreen">
                00
            </td>
            <td class="csstdgreen" rowspan="3">
                John
            </td>
        </tr>
</table>
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Nikhil D
  • 2,479
  • 3
  • 21
  • 41
  • 1
    On which line you are getting this error ? – yogi Jul 04 '12 at 07:32
  • 1
    Why not debug it and see what is null ? is more fast and easy to debug it than ask it. – Aristos Jul 04 '12 at 07:34
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 13 '13 at 02:15

5 Answers5

2

in this part:

<td>
    09:00AM
</td>

there is no class attribute. So you need to check if it is null first:

if (mytable.Rows[i].Cells[j].Attributes["class"] != null &&
    mytable.Rows[i].Cells[j].Attributes["class"].Equals("csstdgreen")) { 

    // other code...

}
Botz3000
  • 39,020
  • 8
  • 103
  • 127
1

How about this ?

    for(int i = 0; i < mytable.Rows.Count; i++)
        {

    string cssClass ;
    for(int j = 0; j < mytable.Rows[i].Cells.Count; j++)
    {

    cssClass = mytable.Rows[i].Cells[j].Attributes["class"];

       if(cssClass != null)
        {
          if(cssClass != String.Empty)
          {}
        }

    }

}

0

I think mytable.Rows[i].Cells[j].Attributes["class"] is null in your case.

You need check this for null

if (mytable.Rows[i].Cells[j].Attributes["class"] != null)
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
0
if(Rows[i] != null)
    if(Cells[j] != null)
       if(Cells[j].Attributes["class"] != null)
JohnnBlade
  • 4,261
  • 1
  • 21
  • 22
0

either check for null as

if (mytable.Rows[i].Cells[j].Attributes["class"] != null)

or add a class attribute in your

<td>      09:00AM  </td>  

part as

<td class="abc">      09:00AM  </td>  
akhil
  • 1,202
  • 3
  • 21
  • 43