Accessing a nested repeater's datasource

2019-07-23 18:04发布

问题:

I have a repeater:

<asp:Repeater ID="rptSessions" runat="server">

Inside this I have another repeater:

<asp:Repeater ID="rptPeople" runat="server" OnItemDataBound="rptPeople_ItemDataBound">

On the ItemDataBound on my parent repeater, I am setting the datasource for the child repeater.

  Dim dtPeople As New DataTable
  dtPeople.Columns.Add("FirstName")
  dtPeople.Columns.Add("LastName")
  dtPeople.Columns.Add("Company")
  If e.Item.DataItem("Lunch") = True Then dtPeople.Columns.Add("Dietary") <-- ***
  rptPeople.DataSource = dtPeople
  rptPeople.DataBind()

Now consider the html for my child repeater

<asp:Repeater ID="rptPeople" runat="server" OnItemDataBound="rptPeople_ItemDataBound">
  <HeaderTemplate>
    <table>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Company</th>
        <asp:Literal ID="litDietaryRequirements" runat="server"><th>Dietary Requirements</th></asp:Literal>
      </tr>
  </HeaderTemplate>
  .....

On the ItemDataBound for my child repeater I would like to hide litDietaryRequirements depending on whether the column Dietary exists in it's datasource. I tried the following:

If e.Item.ItemType = ListItemType.Header Then
  DirectCast(e.Item.FindControl("litDietaryRequirements"), Literal).Visible = DirectCast(e.Item.DataItem, DataRowView).Row.Table.Columns.Contains("Lunch")
End If

e.Item.DataItem seems to be Nothing

回答1:

In the end I did this:

If e.Item.ItemType = ListItemType.Header Then
   Dim LunchRequired As Boolean = DirectCast(DirectCast(e.Item.NamingContainer.NamingContainer, RepeaterItem).DataItem, DataRowView).Row.Item("Lunch")
   DirectCast(e.Item.FindControl("litDietaryRequirements"), Literal).Visible = LunchRequired
End If