Narazana Narazana -4 years ago 69 Question

Access DataLists inside the ListView

I'm OK with C# and VB.nET

I have a DataList (Question) inside the ListView (Section). ListiView is to hold the sections. DataList holds the questions of a section. Let's say I have 3 sections, each section has 2 questions.

<asp:ListView ID="lvSection" runat="server">
<div id="itemPlaceholder" runat="server" />
<asp:HiddenField ID="hfSectionId" runat="server" Value='<%#Eval("SectionId")%>' />
<hr />
<asp:DataList ID="dlQuestion" runat="server" >
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("Question") %>'></asp:Label>
<asp:HiddenField ID="hfQuestionId" runat="server" Value='<%# Eval("QuestionId") %>' />


<asp:Button runat="server" Text="Submit" onclick="Submit_Click" />

I'm trying to access the DataList dlQuestion when the button "Submit" is click like this:

Protected Sub Submit_Click(ByVal sender As Object, ByVal e As EventArgs)
'but I need to loop through all DataLists inside the ListView
'Maybe there are ways to get all the DataLists into a collection and then can loop through each one of them

'this will get only one DataList. Here's the pseudocode

Dim question As DataList = lvSection.FindControl("dlQuestion")
For Each item As DataListItem In quest.Items
Dim questionId As HiddenField = item.FindControl("hfQuestionId")
End Sub

But it does not get anything back, question always gets nohting. I think it's because there are 3 DataList inside the ListView now, due to 3 sections, and it cannot find DataList dlQuestion anymore. How do I access these DataLists of ListView from the code behind? I need to loop through each control of the DataList .

Thank you.

Answer Source

You would need to do it as this:

for each item As ListViewDataItem in lvSection.Items
    Dim list As DataList = item.FindControl("dlQuestion")
    If (list IsNot Nothing) Then
        For Each dlItem As DataListItem In quest.Items

            Dim questionId As HiddenField = dlItem.FindControl("hfQuestionId")

    End If

You have to access the data list in each item in the ListView first, not at the listview level.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download