Результаты Radiobuttonlist не работают при динамическом создании rbl - PullRequest
1 голос
/ 24 февраля 2011

У меня 20 списков радиобуттон, которые создаются динамически, а затем объявляются при отправке формы.

У меня также есть некоторый код, который суммирует количество отвеченных вопросов и общую стоимость отвеченных вопросов. - этот код работал, когда списки радиокнопок были жестко закодированы на странице, но сейчас это не так. - Я пишу количество ответов на вопросы и общую стоимость всех ответов на странице, но они возвращаются как 0.

Кто-нибудь может понять, почему это может не сработать сейчас, когда списки радиобуттон создаются динамически.?

Код позади:

Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)

        For i As Integer = 1 To 20

            Dim TableRow As New TableRow()
            Dim TableRowCell_1 As New TableCell()
            TableRow.Cells.Add(TableRowCell_1)
            holidayQuestionnaireTable.Rows.Add(TableRow)

            Dim question As New RadioButtonList
            question.ID = "question" & i

            question.Items.Insert(0, new listitem("", "1"))
            question.Items.Insert(1, new listitem("", "2"))
            TableRowCell_1.Controls.Add(question)

        Next

End Sub

...

Sub btnSendFeedback_Click(sender as Object, e as EventArgs)

    Dim question1 As RadioButtonList = DirectCast(Page.FindControl("question1"), RadioButtonList)
    Dim question2 As RadioButtonList = DirectCast(Page.FindControl("question2"), RadioButtonList)
    Dim question3 ...
    ...
    Dim question19 As RadioButtonList = DirectCast(Page.FindControl("question19"), RadioButtonList)
    Dim question20 As RadioButtonList = DirectCast(Page.FindControl("question20"), RadioButtonList)

    Dim rblCount As Double
    Dim total As Double
    Dim avg As Double

    For Each ctrl As UI.Control In Me.myPanel.Controls
        If TypeOf ctrl Is RadioButtonList Then
            Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
            If rbl.SelectedIndex > -1 And not rbl.ID = "question18" Then
                Dim value As Double = Double.Parse(rbl.SelectedValue)
                total += value
                rblCount += 1
            End If
        End If
    Next

    Response.Write(rblCount & " - " & total & " - " & (total / rblCount))

End Sub

Тело:

<asp:Placeholder ID="myPanel" runat="server">
        <asp:Table runat="server" CellPadding="0" CellSpacing="0" GridLines="None" HorizontalAlign="Center" CssClass="ratingtable" ID="holidayQuestionnaireTable" />
        <asp:Button OnClick="btnSendFeedback_Click" runat="server" Text="Submit..." ID="submitbutton" />
</asp:Placeholder>

1 Ответ

1 голос
/ 24 февраля 2011

Вы изменили содержимое своей панели и добавили Таблицу вместо того, чтобы использовать Панель для непосредственного добавления RadioButtonLists. FindControl будет смотреть только на NamingContainer панели, а не на дочерние элементы управления NamingContainer. Поиск в коллекции элементов управления Panel также не работает, поскольку списки ресурсов находятся внутри таблицы, которая находится внутри Panel. Поэтому вы должны зациклить TableRows, чтобы получить RBL. Посмотрите:

For Each row As TableRow In Me.holidayQuestionnaireTable.Rows
     For Each cell As TableCell In row.Cells
         For Each ctrl As Control In cell.Controls
             If TypeOf ctrl Is RadioButtonList Then
                Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
                If rbl.SelectedIndex <> -1 AndAlso rbl.ID <> "question18" Then
                   Dim value As Int32 = Int32.Parse(rbl.SelectedValue)
                   total += value
                   rblCount += 1 'count only the selected RadiobuttonLists'
                End If
             End If
         Next
    Next
Next

Если вы хотите использовать FindControl-подход, вы должны использовать NamingContainer каждого radioButtonList, а это TableRow. Так что это также будет работать, но очень статично и подвержено ошибкам:

Dim question1 As RadioButtonList = DirectCast(Me.holidayQuestionnaireTable.Rows(0).FindControl("question1"), RadioButtonList)
Dim question2 As RadioButtonList = DirectCast(Me.holidayQuestionnaireTable.Rows(1).FindControl("question2"), RadioButtonList)
Dim question3 As RadioButtonList = DirectCast(Me.holidayQuestionnaireTable.Rows(2).FindControl("question3"), RadioButtonList)
...