Search code examples
c#asp.netrandomradiobuttonlist

Adding data to a RadioButtonList in a random order


I'm trying to add data to a RadioButtonList in a random order (as shown below in btnGetQuestion_Click), however, on a postback (btnCheck_Click) the selected item in the RadioButtonList changes to a different item the list. Why does this happen and any suggestions as to how to avoid this?

.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)
{
}

Solution

  • In your code to add list item to the list, you are adding multiple list items with the same value 'n'. If you select one of the item with value 'n', after postback one of item with value 'n' will be selected(probably the first one). If you need to keep the proper selection, then you need to bind different values to each checkbox. I think you have to keep the option and value pair in seperate view state variable, bind option 1, option 2... as the value to the radio button list and get the proper value from the viewstate variable during further processing.

    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"));