How to add objects to a RadioButtonList based on r

2019-05-25 03:51发布

问题:

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

回答1:

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]);
}


回答2:

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