我希望添加一段代码,为radiobutton添加一个随机答案,但我无法弄清楚如何将它添加到radiobutton,这样每次加载它时都会显示不同的答案。
我怎样才能让它发挥作用?
到目前为止我使用过的代码:
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())
}
非常感谢任何帮助
由于
答案 0 :(得分: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];
}
}
答案 1 :(得分:0)
您可以将方法中的逻辑包装在将返回RadioButton列表的方法中,然后在每次需要时调用,加载方法。它可能看起来像这样:
var rbs = GetNewRandomListOfRadioButtons(List<string> answers)