简体   繁体   中英

Repeater ItemDataBound NullReferenceException

I am getting a NullReferenceException when there is a null value in my data. There will be many null and empty values in this data and I want to highlight them. col2 is the id of the td

<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";
            }
    }
}

You need to add runat="server" if you want to access a regular html control from code-behind.

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

We use .FindControl if you want to find a child control.

Since HtmlTableCell is a immediate parent of the label control, you need to use .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";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM