Hide child and parent repeater when child repeater is empty
I have a question about repeaters in ASP.net
I have 2 repeaters nested.
I would like to hide both the parent and child repeater when the child repeater has no items. Each parent with its own children provides unique classes such as "class =" childlist_1 ".
ascx file:
<asp:Repeater ID="ParentRepeater" runat="server">
<ItemTemplate>
<ul class="Mainlist">
<li>
<h3 class="selected"><a href="#">List 1</a></h3>
<ul id="DomainList" class="child-items" runat="server">
<asp:Repeater ID="ChildRepeater" runat="server">
<ItemTemplate><li><a href="#">Link to child item</a></li></ItemTemplate>
</asp:Repeater>
</ul>
</li>
</ul>
</ItemTemplate>
</asp:Repeater>
What's the best solution for this?
Thanks in advance!
+1
source to share
2 answers
You can do this in the ItemDataBound event
protected void ParentRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
// code that binds ChildRepeater
.....
// check if ChildRepeater has no items
if (((Repeater)e.Item.FindControl("ChildRepeater")).Items.Count == 0)
{
e.Item.Visible = false;
}
}
}
+2
source to share
If I like to use the bind method of the child relay (i.e. DataSource='<%# GetChildDatasource(Eval("parentID").ToString()) %>'
) it won't work since the datasource is bound after the method of the parent has run.
A workaround is to use the PreRender method on the child relay:
protected void ChildRpt_PreRender(object sender, EventArgs e)
{
//hide if empty
Repeater rpt = (Repeater)sender;
rpt.Visible = rpt.Items.Count > 0;
}
0
source to share