Search code examples
c#asp.netitemtemplateasprepeater

Getting control from Repeater ItemTemplate server-side


I'm trying to use a repeater to make a table. however, there's some logic that I need to implement to some specific controls, says a div, in the items in the repeater.

I've tried this but it didn't work,,, I alwas get:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 35:         HtmlGenericControl myDiv = (HtmlGenericControl)e.Item.FindControl("RepeaterBG");
Line 36: 
Line 37:         myDiv.Style.Add("background-color","green");
Line 38:     }
Line 39: }

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

My Html is:

<asp:Repeater runat="server" ID="MyStudents"
        OnItemDataBound="rptArticleContent_ItemDataBound">
            <HeaderTemplate>
                <table><tr>
            </HeaderTemplate>
            <ItemTemplate> 

                <td>
                    <div  runat="server" ID="RepeaterBG" > helli there</div>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                </td>
                <td>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("RegistrationDate") %>'></asp:Label>
                </td>
                <td>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
                </td>

            </ItemTemplate>
            <FooterTemplate>
                </tr></table>
            </FooterTemplate>
        </asp:Repeater>

my .CS

protected void rptArticleContent_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Label lb = new Label();
    lb.Text = "</tr><tr>";
    e.Item.Controls.Add(lb);

    HtmlGenericControl myDiv = (HtmlGenericControl)e.Item.FindControl("RepeaterBG"); // i get null here, it seems to not find it at all!
    myDiv.Style.Add("background-color","green"); // problem here
}

where did i go wrong?!


Solution

  • You need to check and make sure your item is a data item. If you see in your example link you posted, the first line inside the ItemDataBound event is:

    if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType !=   
           ListItemType.AlternatingItem) return;
    

    IIRC, that's because the first item inside of the ItemDataBound event is a header item. You must do a check to see if the item is a data item.