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

做~自己de王妃 提交于 2019-12-06 10:29:08

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

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