forum

Home / DeveloperSection / Forums / Adding data to a RadioButtonList in a random order

Adding data to a RadioButtonList in a random order

Anonymous User 1715 16-Jan-2015

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


Updated on 16-Jan-2015
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By