0

1ページに20radiobuttonlists枚あります。それぞれに、値が 1、2、3、および 4 の 4 つのオプションがあります。

私がする必要があるのは、フォームを送信することです。すべての合計値radiobuttonlists(例: 3+1+2+3+4...) を、実際に入力された合計数で割った値を取得します (いずれも必要ありません)。フィールドなので、0 から 20 までの任意のフィールドが入力されている可能性があります) - したがって、平均値が得られます。

これを行う簡単でエレガントな方法はありますか?

4

1 に答える 1

1

RadioButtonLists を Panel または他の Container-control に埋め込みます。次に、そのコントロール コレクションをループして、すべての 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 のみをカウントし、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

この RadioButtonList を無視するための追加の制限として追加したことに加えて、ステートメントに移動rblCount += 1しました。If rbl.SelectedIndex <> -1rbl.ID <> "RadioButtonList14"

于 2011-02-11T16:35:08.577 に答える