a1204773
a1204773

Reputation: 7043

Change randomly the button names

I have 4 buttons btn1 btn2 btn3 btn4

q1 = from tAns in db.Questions where tAns.idQuestion == x select tAns;
q2 = from fAns1 in db.Questions where fAns1.idQuestion == x select fAns1;
q3 = from fAns2 in db.Questions where fAns2.idQuestion == x select fAns2;
q4 = from fAns3 in db.Questions where fAns3.idQuestion == x select fAns3;

I need a way that it randomly change the text of button... Possible outputs:

First time

btn1.Text = q2.ToString();
btn2.Text = q4.ToString();
btn3.Text = q3.ToString();
btn4.Text = q1.ToString();

Second time

btn1.Text = q1.ToString();
btn2.Text = q3.ToString();
btn3.Text = q2.ToString();
btn4.Text = q4.ToString();

etc...

Upvotes: 1

Views: 157

Answers (1)

keyboardP
keyboardP

Reputation: 69372

I'm guessing you're creating a quiz app of some sort, so you need to have only be able to pick a random answer once. Instead of picking a string from an array, just throw all the strings into an array and shuffle the array. A quick and easy way of shuffling the array would be to use the Fisher-Yates Shuffle.

Then iterate through the buttons in a for loop and assign the value to your buttons. (You'll need to add the error checking).

for(int i = 0; i < myShuffledArray.Count(); i++)
     myButtonsCollection[i].Text = myShuffledArray[i];

Upvotes: 2

Related Questions