2

I am creating a radio button list in the back end of the system. Is there any method that let me display items with random order ?

My Code :

<asp:radiobuttonlist id="RadioButtonList1" runat="server" 
                                TextAlign="Right" CellPadding="10" RepeatLayout="Table" 
                                CausesValidation="True" CssClass="radioAnswers" ClientIDMode="Static"></asp:radiobuttonlist>

c#

  RadioButtonList1.Items.Add(New ListItem(rsQuestion("a"), "A"))
                RadioButtonList1.Items.Add(New ListItem(rsQuestion("b"), "B"))
                RadioButtonList1.Items.Add(New ListItem(rsQuestion("c"), "C"))
                RadioButtonList1.Items.Add(New ListItem(rsQuestion("d"), "D"))
user3636426
  • 177
  • 1
  • 12
  • There's no built in method for that AFAIK. But that shouldn't be too much of an problem to implement a void AddRadioButtonsRandomOrder(RadioButtonList list, List values) – Kilazur May 14 '14 at 11:43
  • See this: http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp - it's for list rather than radiobuttonlist but could easily be adapted. – sr28 May 14 '14 at 12:06

2 Answers2

2

Using the the random class create a list of number qith a range 1 is the starting and 4 being the table number of radio buttons. create another list with you listitems and then loop through the number list and adding them to the index, as that strating has to be a whole number you have to minus one from numbers list

Random ran = new Random();
var numbers = Enumerable.Range(1, 4).OrderBy(i => ran.Next()).ToList();

List<ListItem> ans= new List<ListItem>();
ans.Add(new ListItem(rsQuestion["a"].ToString(), "A"));
ans.Add(new ListItem(rsQuestion["b"].ToString(), "B"));
ans.Add(new ListItem(rsQuestion["c"].ToString(), "C"));
ans.Add(new ListItem(rsQuestion["d"].ToString(), "D"));

foreach (int num in numbers)
{
    RadioButtonList1.Items.Add(ans[num - 1]);
}
user3086751
  • 205
  • 4
  • 18
0

You have to use 'OrderBy' method to order the data source of your RadioButtonList. And as you want to order it randomly, you have to use a random factor.

For this purpose, you should use 'Random' class in C#.

Use this code : (Place your data source for radio button list instead of 'yourList')

Random ran = new Random();
RadioButtonList1.DataSource = yourList.OrderBy(x => ran.Next()).ToList();