nested dictionary to nested repeater asp.net c#

空扰寡人 提交于 2019-11-30 20:21:21

If you do indeed need to use nested repeaters, its possible, but getting it working isn't particularly obvious. The following would work (simplified for brevity):

<asp:Repeater id="level1" OnItemDataBound="level1_ItemDataBound" ...>
  <ItemTemplate>
    <asp:Repeater id="level2" OnItemDataBound="level2_ItemDataBound" ...>
      <ItemTemplate>
        <asp:Repeater id="level3" OnItemDataBound="level3_ItemDataBound" ...>
        </asp:Repeater>
      </ItemTemplate>
    </asp:Repeater>
  </ItemTemplate>
</asp:Repeater>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    Dictionary<string, Dictionary<string, List<info>>> branch = ...;
    level1.DataSource = branch;
    level1.DataBind();
}

protected void level1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Dictionary<string, List<info>> data = (Dictionary<string, List<info>>)e.Item.DataItem;
    Repeater level2 = e.Item.FindControl("level2") as Repeater;
    level2.DataSource = data;
    level2.DataBind();
}

protected void level2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    List<info> data = (List<info>)e.Item.DataItem;
    Repeater level3 = e.Item.FindControl("level3") as Repeater;
    level3.DataSource = data;
    level3.DataBind();
}

protected void level3_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   // Bind properties from info elements in List<info> here
}

There's an nicer way of doing this without any ItemDataBound events. For simplicity let's assume two level of repeaters.

<asp:Repeater id="level1" >
   <ItemTemplate>
     <asp:Repeater id="level2" 
          DataSource='<%# ((System.Collections.Generic.KeyValuePair<string,System.Collections.Generic.List<string>>)Container.DataItem).Value %>' >
      <ItemTemplate>
           <%# Container.DataItem %>
       </ItemTemplate>
      </asp:Repeater>
   </ItemTemplate>
 </asp:Repeater>

I usually prefer this way, since for some reason I hate ItemDataBound events :)

asp:TreeView? Not sure how it will handle the nested data set but it's designed to display it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!