这是我要知道的代码,选择了哪个单选按钮,但在第6行收到错误。Object reference not set to an instance of an object
Dim selected_option As String = "0"
For i = 1 To 4
Dim rdbName As String = "rb_option" & i
Dim rdb As New RadioButton()
rdb = CType(Me.Page.FindControl(rdbName), RadioButton)
If rdb.Checked = True Then
selected_option = i.ToString
Exit For
End If
Next
有4个标识为rb_option1
,rb_option2
,rb_option3
和rb_option4
的广播按钮。
更新
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table style="width: 100%; height: 100%; margin-bottom: 50px">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td style="width: 95%">
<asp:Label ID="lbl_question" CssClass="frm_label" Text='<%# Eval("QUESTION")%>'runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rb_option1" Checked='<%# IF(Eval("ANSWER")="1",true,false) %>' GroupName="answer" Text='<%# Eval("OPT1") %>' CssClass="frm_label" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rb_option2" Checked='<%# IF(Eval("ANSWER")="2",true,false) %>' GroupName="answer" Text='<%# Eval("OPT2") %>' CssClass="frm_label" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rb_option3" Checked='<%# IF(Eval("ANSWER")="3",true,false) %>' GroupName="answer" Text='<%# Eval("OPT3") %>' CssClass="frm_label" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rb_option4" Checked='<%# IF(Eval("ANSWER")="4",true,false) %>' GroupName="answer" Text='<%# Eval("OPT4") %>' CssClass="frm_label" runat="server" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
提前感谢!!
答案 0 :(得分:3)
为什么不使用RadioButton列表?然后你可以通过以下方式迭代你的单选按钮:
HTML:
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Value="1">Radio 1</asp:ListItem>
<asp:ListItem Value="2">Radio 2</asp:ListItem>
<asp:ListItem Value="3">Radio 3</asp:ListItem>
<asp:ListItem Value="4">Radio 4</asp:ListItem>
</asp:RadioButtonList>
代码:
For i As Integer = 1 To 4
For Each li As ListItem In RadioButtonList1.Items
If li.Selected Then
selected_option = li.Value
End If
Next
Next
如果我的VB.NET语法错误(用于C#),请道歉。
答案 1 :(得分:0)
更改此行:
Dim rdbName As String = "rb_option" & i
到此:
Dim rdbName As String = "ctl00_cpExamMaster_Repeater1_ctl01_rb_option" & i