我的代码隐藏 (c#) 文件使用 while() 循环为数据库中任意给定数量的问题动态声明 RadioButtonLists:
我在 for 循环中向每个 tmpRBL 添加项目。
我将每个 RadioButtonList 注册到一个子面板,该子面板是我在 while() 循环的每次迭代开始时创建的。
然后,我将每个面板添加到父面板。
while(reader.Read()
{
...
RadioButtonList tmpRBL = new RadioButtonList();
temp = "RadioButtonList" + count.ToString();
tmpRBL.ID = temp;
tmpRBL.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Vertical;
tmpRBL.TextAlign = System.Web.UI.WebControls.TextAlign.Left;
...
for (int i = 1; i <= numAnswers; i++)
{
tmpItem = new ListItem("", i.ToString());
tmpRBL.Items.Add(tmpItem);
}
...
p.Controls.Add(tmpRBL);
...
questionPanel.Controls.Add(p);
}
如何检索这些动态创建的 RadioButtonList 的 selectedIndexes?我花了一天的大部分时间尝试网上其他类似问题的各种修复,但没有运气。
如果我在 Chrome 中使用“Inspect Element”,我可以在所需位置看到 RadioButtonLists,表面上带有我分配的 ID(RadioButtonList1、RadioButtonList2 等),但我尝试的所有操作最终都会得到一个 null 对象。
我对 C# 比较陌生,这是我第一次处理动态控件,非常感谢您提供的任何帮助。
基本上,如果动态创建控件,则需要重新加载这些控件(具有相同的 ID)在页面后面的每个帖子中。
否则,它们将变为空,并且您将无法访问它们。
这是一个示例。它加载RadioButtonList
动态控制并在单击按钮时显示所选值。
<asp:PlaceHolder runat="server" ID="PlaceHolder1"/>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" />
<asp:Label runat="server" ID="Label1"/>
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
protected void Button1_Click(object sender, EventArgs e)
{
var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList;
Label1.Text = radioButtonList.SelectedValue;
}
private void LoadControls()
{
var tmpRBL = new RadioButtonList();
tmpRBL.ID = "1";
for (int i = 1; i <= 5; i++)
{
var tmpItem = new ListItem(i.ToString(), i.ToString());
tmpRBL.Items.Add(tmpItem);
}
PlaceHolder1.Controls.Add(tmpRBL);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)