2016-01-07 40 views
0

我正在尋找添加一個代碼片斷,爲單選按鈕添加一個隨機答案,但我不知道如何讓它添加到單選按鈕,這樣每次你加載它會顯示不同的答案。如何添加一個單選按鈕的隨機答案

我該如何去做到這一點才能使其運行?

到目前爲止,我所使用的代碼:

List<string> answers = new List<string>(); 
answers.Add("1 Byte"); 
answers.Add("1 KiloByte"); 
answers.Add("1 PetaByte"); 
answers.Add("1 MegaByte"); 

Random rnd = new Random(); 
string[] MyRandomArray = answers.OrderBy(x => rnd.Next()).ToArray(); 

List<RadioButton> rbs = new List<RadioButton>(); 
rbs.Add(rb1); 
rbs.Add(rb2); 
rbs.Add(rb3); 
rbs.Add(rb4); 

foreach (string s in MyRandomArray) 
{ 
    rbs.Add(s.ToString()) 
} 

任何幫助,將不勝感激

感謝

+1

*每次*什麼*加載?在你使Random對象成爲全局變量之後,你所需要做的就是從MyRandomArray中設置'rbX.Text';其餘的是殘餘的 – Plutonix

+0

以及你試圖添加一個'字符串'列表',不要那樣做 – Jonesopolis

+0

你知道如何去做嗎? – Rariolu

回答

0

假設你希望它的每個表單的一個新實例被調用時重置,在你的表單中使用下面的構造函數(在這個例子中我稱之爲「MainForm」形式)。首先,確保您的單選按鈕的名稱相似。下面我將創建它們,但您應該在Visual Studio中使用Designer。

private RadioButton rb1; 
private RadioButton rb2; 
private RadioButton rb3; 
private RadioButton rb4; 

然後在窗體中使用這個構造函數。

public MainForm() 
{ 
    InitializeComponent();//Adding the radio buttons to form. 
    List<string> awnsers = new List<string>(); 
    awnsers.Add("1 Byte"); 
    awnsers.Add("1 KiloByte"); 
    awnsers.Add("1 PetaByte"); 
    awnsers.Add("1 MegaByte"); 
    Random rnd = new Random(); 
    string[] MyRandomArray = awnsers.OrderBy(x => rnd.Next()).ToArray(); 
    for(int i = 0; i < awnsers.Length; i++) 
    { 
     Controls.Find("rb"+(i+1),true).FirstOrDefault().Text = MyRandomArray[i]; 
    } 
} 
0

你可以用你的邏輯在隨機分組的方法,將每次你需要它的時候返回列表單選按鈕,然後調用,負載的方法。它可能看起來像這樣:

var rbs = GetNewRandomListOfRadioButtons(List<string> answers) 
相關問題