0

With the help of this answer posted before (How to add objects to a RadioButtonList based on random order ?), I can add items to a RadioButtonList in a random order.

However, it's nested in a loop so how would I 'reset' this order so that subsequent items are not added in the same order as show by this screen cap(https://i.stack.imgur.com/cRHDk.jpg).

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();
}
Community
  • 1
  • 1
Bhav
  • 1,957
  • 7
  • 33
  • 66

1 Answers1

0

You should initialize the variable "ran" outside the loop. And also, you should pass a seed in the constructor like this:

Random ran = new Random(Guid.NewGuid().GetHashCode());
David
  • 325
  • 3
  • 12
  • Thanks. I've initialized 'ran' outside the loop and it works. So I should also enter the above line of code outside the loop? What's the effect of this/why should I do this? – Bhav Jul 06 '14 at 18:46
  • If you prefer, you can use the constructor of the Random class without parameters, which internally uses a time-dependent default seed value. More info [here](http://msdn.microsoft.com/en-us/library/System.Random.Random(v=vs.110).aspx) – David Jul 06 '14 at 18:55