当我尝试在MainPage构造函数中执行下面的代码时,它完美地运行。但是当我在一些Button_Click方法下放置相同的代码时,它会给我一个错误 - Stack1.Children.Add(shuffleRadio [1]);
它是一个带有随机选项生成和代码内单选按钮生成的测验。
private void Button_Click(object sender, RoutedEventArgs e)
{
questions = questionset.ToList<String>();
answers = answerset.ToList<String>();
try
{
tr = randomizer.Next(4);
que.Text = questions[tr].ToString();
questions.RemoveAt(tr);
RadioButton ra1 = new RadioButton();
ra1.Name = "ans1";
ra1.Content = answers[tr].ToString();
ra1.GroupName = "Group1";
ra1.Checked += RadioButton_Checked;
answers.RemoveAt(tr);
RadioButton ra2 = new RadioButton();
rand = randomizer.Next(5);
ra2.Name = "ans1";
ra2.Content = answers[rand].ToString();
ra2.GroupName = "Group1";
ra2.Checked += RadioButton_Checked;
answers.RemoveAt(rand);
RadioButton ra3 = new RadioButton();
rand = randomizer.Next(3);
ra3.Name = "ans1";
ra3.Content = answers[rand].ToString();
ra3.GroupName = "Group1";
ra3.Checked += RadioButton_Checked;
answers.RemoveAt(rand);
RadioButton ra4 = new RadioButton();
rand = randomizer.Next(2);
ra4.Name = "ans1";
ra4.Content = answers[rand].ToString();
ra4.GroupName = "Group1";
ra4.Checked += RadioButton_Checked;
answers.RemoveAt(rand);
List<RadioButton> shuffleRadio = new List<RadioButton>();
shuffleRadio.Add(ra1);
shuffleRadio.Add(ra2);
shuffleRadio.Add(ra3);
shuffleRadio.Add(ra4);
Random rng = new Random();
int r = shuffleRadio.Count;
while (r > 1)
{
r--;
int tem = rng.Next(r + 1);
RadioButton value = shuffleRadio[tem];
shuffleRadio[tem] = shuffleRadio[r];
shuffleRadio[r] = value;
}
Stack1.Children.Add(shuffleRadio[0]);
Stack1.Children.Add(shuffleRadio[1]); //The error is here
Stack1.Children.Add(shuffleRadio[2]);
Stack1.Children.Add(shuffleRadio[3]);
}
catch (Exception erg)
{
MessageBox.Show(erg.ToString());
}
}
答案 0 :(得分:0)
这是因为我在stackpanel中添加的内容与以前的内容重复了
foreach (var itm in shuffleRadio)
{
RadioButton ra = new RadioButton();
ra.Content = itm.Content.ToString();
ra.GroupName = "Group1";
ra.Checked += RadioButton_Checked;
Stack1.Children.Add(ra);
}