1

这是我要知道的代码,选择了哪个单选按钮,但在第 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 个带有 ID rb_option1rb_option2rb_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>

预先感谢 !!

4

2 回答 2

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#)。

于 2012-08-02T13:42:23.183 回答
0

更改此行:

Dim rdbName As String = "rb_option" & i

对此:

Dim rdbName As String = "ctl00_cpExamMaster_Repeater1_ctl01_rb_option" & i
于 2012-08-02T13:58:59.690 回答