How to add objects to a RadioButtonList based on random order ?

北城余情 提交于 2019-12-22 12:41:10

问题


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


来源:https://stackoverflow.com/questions/23653485/how-to-add-objects-to-a-radiobuttonlist-based-on-random-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!