你调用的对象是空的。

时间:2012-07-04 07:30:03

标签: c# asp.net nullreferenceexception

我在循环表中查找单元格有csstdgreen。我给出一个错误对象引用未设置为对象的实例。

 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>

5 个答案:

答案 0 :(得分:2)

在这一部分:

<td>
    09:00AM
</td>

没有class属性。所以你需要先检查它是null

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

    // other code...

}

答案 1 :(得分:1)

这个怎么样?

    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)
          {}
        }

    }

}

答案 2 :(得分:0)

我认为mytable.Rows[i].Cells[j].Attributes["class"]在你的案例中是null

您需要针对null

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

检查null为

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

或在

中添加一个class属性
<td>      09:00AM  </td>  

部分为

<td class="abc">      09:00AM  </td>