havin havin - 4 months ago 16
ASP.NET (C#) Question

How to retrieve a button inside a ListView which is inside a Repeater

I want to access the button

btn3
inside a ListView. The ListView itself is in the ItemTemplate of a Repeater.

<asp:Repeater runat="server" ID="rep1">
<ItemTemplate>
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
...
<asp:Button ID="btn3" runat="server" Text='<%#Eval("likes").ToString()%>'/>
...
</asp:ListView>
</ItemTemplate>
</asp:Repeater>


When I try to access
btn3
in the
ItemDataBound
event of the Repeater, the returned value is null:

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn1 = (Button)e.Item.FindControl("Btn3"); // btn1 is null
}
}

Answer

You can set the ItemDataBound event handler of the ListView:

<asp:Repeater runat="server" ID="rep1">
    <ItemTemplate>
        <asp:ListView ID="ListView1" runat="server" OnItemDataBound="ListView1_ItemDataBound" DataSourceID="SqlDataSource1">
            ...
        </asp:ListView>
    </ItemTemplate>
</asp:Repeater>

And retrieve the button in code-behind:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        Button btn3 = e.Item.FindControl("btn3") as Button;
        ...
    }
}


If you want to do it in the Repeater ItemDataBound event handler (but I am not sure if the ListView is populated at that point):

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{       
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        ListView ListView1 = e.Item.FindControl("ListView1") as ListView;

        foreach (ListViewItem lvItem in ListView1.Items)
        {
            Button btn3 = lvItem.FindControl("Btn3") as Button;
            ...
        }
    }
}
Comments