访问ListView中的DataLists

时间:2011-10-27 11:15:43

标签: c# asp.net vb.net listview datalist

  

我对C#和VB.nET

没关系

我在ListView(Section)中有一个DataList(Question)。 ListiView用于保存这些部分。 DataList包含一节的问题。假设我有3个部分,每个部分有2个问题。

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

<br/>

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

当按下“提交”按钮时,我正在尝试访问DataList dlQuestion:

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")
     Next
     End Sub

但它没有得到任何回报,问题总是没有。我认为这是因为现在ListView中有3个DataList,由于3个部分,它再也找不到DataList dlQuestion了。如何从后面的代码访问ListView的这些DataLists?我需要循环遍历DataList的每个控件。

谢谢。

1 个答案:

答案 0 :(得分:2)

你需要这样做:

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")

        Next
    End If
Next

您必须首先访问ListView中每个项目的数据列表,而不是列表视图级别。