中继器ItemDataBound NullReferenceException

时间:2018-09-11 20:48:48

标签: c# asp.net c#-4.0

当我的数据中有一个空值时,我得到一个NullReferenceException。此数据中将有许多空值和空值,我想突出显示它们。 col2是td的ID

<td id="col2"><asp:Label ID="ESubject" Text='<%# (Eval("EventSubject") == null) ? "null" : Eval("EventSubject") %>' runat="server" /></td>
protected void myRepeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    { 
            var varSubject = e.Item.FindControl("ESubject");
            var adjSubject = varSubject.ToString();

            HtmlTableCell td = (HtmlTableCell)e.Item.FindControl("col2");

            if (adjSubject == "null")
            {
                td.BgColor = "yellow";
            }
    }
}

1 个答案:

答案 0 :(得分:2)

如果要从代码隐藏访问常规html控件,则需要添加runat="server"

<td id="col2" runat="server">
   ...
</td>

如果您要查找子控件,请使用.FindControl

由于HtmlTableCell是标签控件的立即父级,因此您需要使用.Parent

protected void myRepeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var varSubject = e.Item.FindControl("ESubject");
        var adjSubject = varSubject.Parent as HtmlTableCell;
        if (adjSubject != null)
        {
            adjSubject.BgColor = "yellow";
        }
    }
}