views:

94

answers:

1

I have a repeater inside a panel.
Inside this repeater I have another panel.Upon certain conditions, I want to set this panel.visibility = false.

In the code behind, I try locating the panels on OnItemDataBound and set visible=false. But it only returns Object reference not set to an instance of an object.. I guesing it's because it can't locate the panel.

Here is my code:

    <asp:Panel ID="Panel1" runat="server">
        <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="repComments_OnDataBound">    
             <ItemTemplate>                         
                <div>
                   <asp:Panel runat="server" ID="commentAdminPanel" CssClass="floatRight" >
                     <img id='deleteComment' class='deleteComment' src='/img/delete1.jpg' />  
                   </asp:Panel>                     
                </div>
              </div>
            </ItemTemplate>
         </asp:Repeater>
     </asp:Panel>

And here is my code behind:

    protected void repComments_OnDataBound(Object sender, RepeaterItemEventArgs e)
    {
        Panel panel = (Panel)Repeater1.FindControl("commentAdminPanel");
        panel.Visible = false;
    }

What am I doing wrong?

+3  A: 

One issue is that you are calling the repeater directly, instead of the bound item template - e.Item.FindControl instead of Repeater1.FindControl.

The other issue is that the ItemDataBound event will also fire for header and footer, and you are not checking the type of list item (ListItemType enum) you are on in the repeater.

Since you don't have a header item (which would be the first item to call the handler), there is no panel control and the cast fails.

You only need the Item and AlternatingItem item types:

protected void repComments_OnDataBound(Object sender, RepeaterItemEventArgs e)
{
    if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
    {
        Panel panel = (Panel)e.Item.FindControl("commentAdminPanel");
        panel.Visible = false;
    }
}
Oded
Shouldn't it be e.Item.FindControl instead of Repeater1.FindControl
Vedran
@Vedran - quite correct. Thanks for the correction.
Oded
Yes Vedran, it's `e.Item`. Thanks Oded. It worked :)
Steven