0

radiobuttonlists一页有 20 个。每个都有 4 个选项,值为 1、2、3 和 4。

我需要做的是在提交表格时,将所有radiobuttonlists(例如3+1+2+3+4...)的总值除以实际填写的总数(都不需要)字段,因此可以填写从 0 到 20 的任何内容) - 因此获得平均值。

有没有一种简单/优雅的方式来做到这一点?

4

1 回答 1

1

我会将 RadioButtonLists 嵌入到面板或其他容器控件中。然后你可以循环它的控件集合来获取所有的 RadioButtonLists。

您想除以 RBL 的数量还是除以所选 RBL 的数量?

除以 RBL-Count 的示例,因此计数未选择为零,并四舍五入到下一个整数:

aspx:

   <asp:Panel ID="OptionPanel" runat="server">
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
            <asp:ListItem Text="1" Value="1"></asp:ListItem>
            <asp:ListItem Text="2" Value="2"></asp:ListItem>
            <asp:ListItem Text="3" Value="3"></asp:ListItem>
            <asp:ListItem Text="4" Value="4"></asp:ListItem>
        </asp:RadioButtonList>
        <!-- and so on ... -->
    </asp:Panel>
    <asp:Button ID="BtnCalculate" runat="server" Text="calculate average value" />
    <asp:Label ID="LblResult" runat="server" Text=""></asp:Label>

在代码隐藏中:

    Protected Sub BtnCalculate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnCalculate.Click
        Dim rblCount As Int32
        Dim total As Int32
        Dim avg As Int32
        For Each ctrl As UI.Control In Me.OptionPanel.Controls
            If TypeOf ctrl Is RadioButtonList Then
                rblCount += 1
                Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
                If rbl.SelectedIndex <> -1 Then
                    Dim value As Int32 = Int32.Parse(rbl.SelectedValue)
                    total += value
                End If
            End If
        Next
        If rblCount <> 0 Then
            avg = Convert.ToInt32(Math.Round(total / rblCount, MidpointRounding.AwayFromZero))
        End If
        Me.LblResult.Text = "Average: " & avg
    End Sub

根据您只需要计算所选 RadioButtonLists 并完全忽略 fe RadioButtonList14 的新信息,看看:

If rbl.SelectedIndex <> -1 AndAlso rbl.ID <> "RadioButtonList14" Then
   Dim value As Int32 = Int32.Parse(rbl.SelectedValue)
   total += value
   rblCount += 1 'count only the selected RadiobuttonLists'
End If

我已经rblCount += 1进入If rbl.SelectedIndex <> -1-Statement,此外我还添加rbl.ID <> "RadioButtonList14"了忽略此 RadioButtonList 的附加限制。

于 2011-02-11T16:35:08.577 回答