我无法从我在代码文件中动态创建的RadionButtonsList中获取SelectedValue。我将它添加到aspx页面上的PlaceHolder控件。在PostBack之后,单选按钮会在页面上保留其选择,但我无法从代码文件中获取值。
我知道我可以在HTML页面中创建RadioButtonsList,但我需要了解如何仅从代码文件中完成此操作。我遇到的真正问题更复杂。 (创建动态数量的真/假RadioButtonsList控件)
quiz.aspx
<%@ Page Title="Quiz" MasterPageFile="~/MasterPage.master" Language="VB" CodeFile="quiz.aspx.vb" Inherits="quiz" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:PlaceHolder ID="testholder" runat="server"></asp:PlaceHolder>
<asp:Button ID="lblNext" runat="server" type="submit" Text="Next" accesskey="n"/>
</asp:Content>
MasterPage.master
<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>
quiz.aspx.vp
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim testlist As New RadioButtonList
testlist.Items.Add(New ListItem("test 1", "test1"))
testlist.Items.Add(New ListItem("test 2", "test2"))
testholder.Controls.Add(testlist)
If (IsPostBack) Then
Debug.WriteLine("testlist: " & testlist.SelectedValue)
End If
End Sub
提交后的输出是:&#34; testlist:&#34;。有什么想法吗?
答案 0 :(得分:1)
您必须在触发page_load事件之前加载控件,以便loadpostbackdata有机会加载动态控件的视图状态。
将动态控件移动到page_init事件后,我能够看到所选的值。
Dim testlist As New RadioButtonList
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
{
testlist.Items.Add(new ListItem("test1", "test1"))
testlist.Items.Add(new ListItem("test2", "test2"))
testholder.Controls.Add(testlist)
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
{
If (IsPostBack) Then
Debug.WriteLine(testlist.SelectedValue)
End If
}