借助之前发布的答案(How to add objects to a RadioButtonList based on random order ?),我可以随机顺序将项目添加到RadioButtonList。
然而,它嵌套在一个循环中,所以我将如何重置'此订单不会按照此屏幕上限(http://imgur.com/goFNfG2)显示的顺序添加后续商品。
try
{
conn.Open();
string cmdText = "SELECT * FROM questions ORDER BY RAND() LIMIT 5";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
reader = cmd.ExecuteReader();
int i = 0;
while (reader.Read())
{
if (!(list.Contains(reader["question_id"].ToString())))
{
list.Add(reader["question_id"].ToString());
((Label)this.FindControl("lblQuestion" + (i + 1))).Text = reader["question"].ToString();
Random ran = new Random();
var numbers = Enumerable.Range(1, 5).OrderBy(j => ran.Next()).ToList();
List<ListItem> ans = new List<ListItem>();
ans.Add(new ListItem(reader["answer1"].ToString(), "y"));
ans.Add(new ListItem(reader["answer2"].ToString(), "n1"));
ans.Add(new ListItem(reader["answer3"].ToString(), "n2"));
ans.Add(new ListItem(reader["answer4"].ToString(), "n3"));
ans.Add(new ListItem(reader["answer5"].ToString(), "n4"));
foreach (int num in numbers)
{
((RadioButtonList)this.FindControl("rblAnswers" + (i + 1))).Items.Add(ans[num - 1]);
}
i++;
}
}
reader.Close();
}
catch
{
lblError.Text = "Database connection error - failed to insert record.";
}
finally
{
conn.Close();
}
答案 0 :(得分:0)
你应该初始化变量&#34; ran&#34;在循环之外。而且,您应该在构造函数中传递种子,如下所示:
Random ran = new Random(Guid.NewGuid().GetHashCode());