以随机顺序向RadioButtonList添加数据

本文关键字:添加 数据 RadioButtonList 随机 顺序 | 更新日期: 2023-09-27 18:11:33

我试图以随机顺序将数据添加到RadioButtonList(如下面的btnGetQuestion_Click所示),但是,在回发(btnCheck_Click)中,RadioButtonList中的选定项目更改为列表中的不同项目。为什么会发生这种情况,有没有建议如何避免这种情况?

. aspx:

<form id="form1" runat="server">
<div>
    <asp:Button ID="btnGetQuestion" runat="server" Text="Get Question" OnClick="btnGetQuestion_Click" />
    <asp:Label ID="lblQuestion" runat="server" Text=""></asp:Label>
    <asp:RadioButtonList ID="rblQuestions" runat="server"></asp:RadioButtonList>
    <asp:Button ID="btnCheck" runat="server" Text="Check Answer" OnClick="btnCheck_Click" />
    <asp:Label ID="lblAnswer" runat="server" Text=""></asp:Label>
    <asp:Label ID="lblError" runat="server" Text=""></asp:Label>
</div>
</form>
c#:

protected void btnGetQuestion_Click(object sender, EventArgs e)
{
    Random ran = new Random();
    var numbers = Enumerable.Range(1, 5).OrderBy(i => ran.Next()).ToList();
    List<ListItem> ans = new List<ListItem>();
    ans.Add(new ListItem("option 1", "y"));
    ans.Add(new ListItem("option 2", "n"));
    ans.Add(new ListItem("option 3", "n"));
    ans.Add(new ListItem("option 4", "n"));
    ans.Add(new ListItem("option 5", "n"));
    foreach (int num in numbers)
    {
        rblQuestions.Items.Add(ans[num - 1]);
    }
}
protected void btnCheck_Click(object sender, EventArgs e)
{
}

以随机顺序向RadioButtonList添加数据

在将列表项添加到列表的代码中,您正在添加具有相同值'n'的多个列表项。如果选择值为"n"的项之一,则回发后将选择值为"n"的项之一(可能是第一个)。如果需要保持正确的选择,则需要为每个复选框绑定不同的值。我认为你必须保持选项和值对在单独的视图状态变量,绑定选项1,选项2…作为单选按钮列表的值,并在进一步处理时从viewstate变量获取适当的值。

ans.Add(new ListItem("option 1", "y"));
ans.Add(new ListItem("option 2", "n"));
ans.Add(new ListItem("option 3", "n"));
ans.Add(new ListItem("option 4", "n"));
ans.Add(new ListItem("option 5", "n"));