我在页面上有20 radiobuttonlists
。每个都有4个选项,值为1,2,3和4.
我需要做的是提交表格,获取所有radiobuttonlists
的总价值(例如3 + 1 + 2 + 3 + 4 ......)除以实际已经存在的总数填写(没有一个是必填字段,因此可以填写0到20之间的任何内容) - 因此获得平均值。
这样做有简单/优雅的方法吗?
答案 0 :(得分:1)
我会将RadioButtonLists嵌入Panel或其他Container控件中。然后你可以循环其控件集合来获取所有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并忽略f.e. 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
- 语句中,此外我已添加rbl.ID <> "RadioButtonList14"
作为额外限制以忽略此RadioButtonList。