嵌套中继器不会显示列表中的绑定信息

本文关键字:绑定 信息 列表 显示 中继器 嵌套 | 更新日期: 2023-09-27 18:29:53

我正在尝试使用中继器获得一个以行布局显示信息的页面。我有一个工作允许我动态创建超链接,但我无法让我的嵌套中继器显示文件创建的日期。是否可以使用中继器来动态显示列表中的多个变量,就像我下面要做的那样?

.aspx

<asp:Repeater id="repLinks" runat="server">
   <ItemTemplate>
       <tr><td>
      <asp:HyperLink runat="server" NavigateUrl='<%# Container.DataItem.ToString() %>' Text="<%# Container.DataItem.ToString().Split('''').Last() %>"  />    
            <td>  
               <asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="Repeater2_ItemDataBound" >
                  <ItemTemplate>
                   <%# Container.DataItem.ToString()%>  
                     </ItemTemplate> 
               </asp:Repeater>             
           </td>
           <td>
               Submitted By <!--add repeater-->
           </td>
           <td>
               Mark as Billed <!--add repeater-->
           </td>
           </td></tr>
            </ItemTemplate>
           </asp:Repeater>

.aspx.cs

public List<string> CD = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        //Welcomes User
        string Uname = Environment.UserName;
        UserName.Font.Size = 17;
        UserName.Text = "Welcome: " + Uname;
        //gives path and constructs lists for directory paths and file links
        string root = "C:''Users''James''Documents''Visual Studio 2015''WebSites";
        List<string> lLinks = new List<string>();
        //adds files to list
        foreach (var path in Directory.GetDirectories(@root))
        {
            foreach (var path2 in Directory.GetFiles(path))
            {
                lLinks.Add(path2);
                CD.Add(File.GetCreationTime(path2).Date.ToString("yyyy-mm-dd"));
            }
        }
        //Define your list contents here 
        repLinks.DataSource = lLinks;
        repLinks.DataBind();
    }
    protected void Repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater Repeater2 = (Repeater)(e.Item.FindControl("Repeater2"));
            Repeater2.DataSource = CD;
            Repeater2.DataBind();
        }
    }

嵌套中继器不会显示列表中的绑定信息

代码的问题是,您正在绑定Repeater2转发器本身的ItemDataBound事件中的嵌套转发器控件(Repeater2),该控件永远不会被激发,因为当集合中的每个项绑定到转发器控件时,都会激发ItemDataBound事件。

您应该在父中继器的ItemDataBound事件中这样写逻辑:-

<asp:Repeater id="repLinks" runat="server" OnItemDataBound="Repeater1_ItemDataBound">

然后,在这个事件处理程序中写入逻辑:-

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || 
                                      e.Item.ItemType == ListItemType.AlternatingItem)
   {
        Repeater Repeater2 = (Repeater)(e.Item.FindControl("Repeater2"));
        Repeater2.DataSource = CD;
        Repeater2.DataBind();
   }
}

此外,在Page_Load事件中,您应该仅在初始页面加载时绑定父中继器Repeater1,以便将其封装在!IsPostBack中并填充数据源lLinks&CD是在Page_Load事件中执行此操作的独立方法。