来自动态创建的单选按钮列表的 SelectedValue vb

SelectedValue from dynamically created radiobuttonlist vb

我试图在 Visual Studio 2012 年创建一个测验网页,但在 table.

中从动态创建的单选按钮列表中获取所选值时遇到了一些问题

这就是我创建单选按钮列表的方式(并将其添加到 table)

Dim NewRow As New TableRow
Dim NewCell As New TableCell
Dim rblOptions As New RadioButtonList
rblOptions.ID = "Option" & intQuestion.ToString
NewCell.Controls.Add(rblOptions)
NewRow.Cells.Add(NewCell)
'Questions is a table
Questions.Rows.Add(NewRow)

这就是我在用户点击按钮后尝试从单选按钮列表中获取所选值的方式。

Dim rbl As RadioButtonList = DirectCast(Page.FindControl("Option" & intQuestion.ToString), RadioButtonList)

If rbl.SelectedValue.ToString = sdrGetQuestions.Item(0).ToString Then
            intScore += 1
End If

在这两种情况下,变量 intQuestion = 0。 当运行程序我遇到错误:

Object reference not set to an instance of an object.

这一行:

If rbl.SelectedValue.ToString = sdrGetQuestions.Item(0).ToString Then

我认为这显然意味着程序找不到它必须放在 rbl 中的控件。我在网上找不到任何答案...

谁能给我指出正确的方向?

这是我的 .aspx 代码。

<asp:Table ID="Questions" runat="server">

</asp:Table>
<asp:Button ID="SaveButton" runat="server" Text="Save" />

这是我的文件代码背后的代码。 我添加了动态下拉列表。 单击保存按钮时,我正在检索选定的值。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim NewRow As New TableRow
    Dim NewCell As New TableCell
    Dim rblOptions As New RadioButtonList
    rblOptions.ID = "Option1"

    rblOptions.Items.Add(New System.Web.UI.WebControls.ListItem("1", "1"))
    rblOptions.Items.Add(New System.Web.UI.WebControls.ListItem("2", "2"))
    rblOptions.Items.Add(New System.Web.UI.WebControls.ListItem("3", "3"))

    NewCell.Controls.Add(rblOptions)
    NewRow.Cells.Add(NewCell)
    'Questions is a table
    Questions.Rows.Add(NewRow)

End Sub

Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
    If Page.IsValid Then
        Dim rbl As RadioButtonList = DirectCast(Questions.FindControl("Option1"), RadioButtonList)

        If rbl.SelectedValue.ToString = "ExpectedValue" Then

        End If
    End If
End Sub