我正在动态创建一个表,在每行中放置一个动态创建的radiobuttonlist。
然后,我想在单击提交按钮时在页面上显示结果。
我收到一条错误消息,指出
'question1'未声明
为什么会发生这种情况?我在下面列出了所有代码。
代码背后:
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
For i As Integer = 1 To 3
Dim TableRow As New TableRow()
Dim TableRowCell_1 As New TableCell()
TableRowCell_1.Text = i
Dim TableRowCell_2 As New TableCell()
TableRow.Cells.Add(TableRowCell_1)
TableRow.Cells.Add(TableRowCell_2)
QuestionnaireTable.Rows.Add(TableRow)
Dim question As New RadioButtonList
question.ID = "question" & i
question.RepeatColumns = "2"
question.Items.Insert(0, new listitem("", "1"))
question.Items.Insert(1, new listitem("", "2"))
TableRowCell_3.Controls.Add(question)
Next
End Sub
Sub btnSendFeedback_Click(sender as Object, e as EventArgs)
Dim question1 As RadioButtonList = DirectCast(Page.FindControl("question1"), RadioButtonList)
Dim question2 As RadioButtonList = DirectCast(Page.FindControl("question2"), RadioButtonList)
Dim question3 As RadioButtonList = DirectCast(Page.FindControl("question3"), RadioButtonList)
Response.write(question1.SelectedValue & " - " & question2.SelectedValue & " - " & question3.SelectedValue)
End Sub
身体:
<asp:Table runat="server" ID="QuestionnaireTable" />
<asp:Button OnClick="btnSendFeedback_Click" runat="server" Text="Submit..." ID="submitbutton" />
答案 0 :(得分:2)
我可以看到你没有在任何地方声明:)
由于“问题1”是您的ID,您必须使用FindControl找到它。
Page.FindControl(myId)
如果您只有3个项目,可以在当前对象中定义它以便更好地使用。
private question1 as RadioButtonList
private question2 as RadioButtonList
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
me.question1 = new RadioButtonList
End Sub
Sub btnSendFeedback_Click(sender as Object, e as EventArgs)
dim value = me.question1.selectedValue
End Sub
或者你可以做这样的事情
private rbls as new List(of RadioButtonList)
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
dim list1 as new RadioButtonList
list.items.add...
rbls.add(list)
End Sub
Sub btnSendFeedback_Click(sender as Object, e as EventArgs)
For Each _item in Me.rbls
Response.write(_item.SelectedValue)
End For
End Sub
答案 1 :(得分:1)
当您在标记中声明控件时,Visual Studio和ASP.NET会使它成为可以在代码隐藏中访问该控件的。
当你像这样动态地声明一个控件时,你必须从代码隐藏中进行访问。
有多种方法可以做到这一点,可能最简单的方法是:
Dim question1 As RadioButtonList = DirectCast(Page.FindControl("question1"), RadioButtonList)