我有一个包含问题的表和一堆动态创建的单选按钮列表,我试图编写代码,循环遍历每个单选按钮列表并获取所选问题值和相应问题ID的值。我有以下代码返回选定的单选按钮列表值。我将获得问题ID以及他们选择的值?
For Each ctrl As Control In form1.Controls
If TypeOf ctrl Is RadioButtonList Then
Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
For i As Integer = 0 To rbl.Items.Count - 1
If rbl.Items(i).Selected Then
Dim value As String = rbl.SelectedValue
End If
Next
End If
Next
答案 0 :(得分:1)
创建单选按钮时,应将它们放入字典中(确保在Init
阶段执行此操作)。假设String
键包含问题ID:
Dim radios As New Dictionary(Of String, RadioButtonList)
Dim table As DataTable
Sub Page_Init(sender As Object, e As EventArgs)
table = ...
For Each row As DataRow In table.Rows
Dim rbl As New RadioButtonList
' add radio buttons to rbl
radios.Add(row("id").ToString, rbl)
Next
End Sub
然后在用于检索答案的事件处理程序中,您可以轻松访问它们:
Sub MyHandler(sender As Object, e As EventArgs)
For Each row As DataRow In table.Rows
Dim value As String = GetAnswer(row("id").ToString)
' do something with the answer ...
Next
End Sub
Function GetAnswer(id As String) As String
For Each item In radios(id)
If item.Selected Then Return item.SelectedValue
Next
Return Nothing
End Function