我正在做一个简单的测试程序,但是当我关闭窗体的关闭按钮时(窗口右上方的正常按钮,而不是按钮)我自己)。关闭C上的窗体时发生错误#
这是代码,注释只是为了识别的人:
public partial class Preguntas : Form
{
int i = 0;
int j = 0;
int[] score = {
/*Vir*/ 0,
/*Eva*/ 0,
/*Pedro*/ 0 };
string[] questions = new string[] {
/*Vir*/ "¿Qué prefiero ver?","2","3","4","5",
/*Eva*/ "a","2","3","4","5",
/*Pedro*/ "1","2","3","4","5",
};
string[] opt1 = new string[] {
/*Vir*/ "Películas de serie B","2","3","4","5",
/*Eva*/ "1","2","3","4","5",
/*Pedro*/ "1","2","3","4","5",
};
string[] opt2 = new string[] {
/*Vir*/ "Series","2","3","4","5",
/*Eva*/ "1","2","3","4","5",
/*Pedro*/ "1","2","3","4","5",
};
string[] opt3 = new string[] {
/*Vir*/ "Películas romanticas","2","3","4","5",
/*Eva*/ "1","2","3","4","5",
/*Pedro*/ "1","2","3","4","5",
};
string[] opt4 = new string[] {
/*Vir*/ "Películas de acción","2","3","4","5",
/*Eva*/ "1","2","3","4","5",
/*Pedro*/ "1","2","3","4","5",
};
int[] correctAnswer = {
/*Vir*/ 1,1,1,1,1,
/*Eva*/ 1,1,1,1,1,
/*Pedro*/ 1,1,1,1,1
};
public Preguntas()
{
InitializeComponent();
RefreshTest();
}
public void FinishTest()
{
i = 0; // I dont know why i have to put this but if not
j = 0; // a axception when close the program occurs.
Resultado f2 = new Resultado(score);
this.Hide();
f2.ShowDialog();
this.Close();
}
public void RefreshTest()
{
if (i == 15) FinishTest();
pictureBox1.Image = imageList1.Images[i];
pictureBox2.Image = imageList2.Images[j];
label1.Text = opt1[i];
label2.Text = opt2[i];
label3.Text = opt3[i];
label4.Text = opt4[i];
label5.Text = questions[i];
}
public void Correction(int answer)
{
if(correctAnswer[i] == answer)
{
score[j] += 1;
}
if (++i % 5 == 0) j++;
RefreshTest();
}
private void button1_Click(object sender, EventArgs e)
{
Correction(1);
}
private void button2_Click(object sender, EventArgs e)
{
Correction(2);
}
private void button3_Click(object sender, EventArgs e)
{
Correction(3);
}
private void button4_Click(object sender, EventArgs e)
{
Correction(4);
}
}
这是个例外:
类型“System.ArgumentOutOfRangeException”未处理的异常发生在System.Windows .Forms.dll
附加信息:InvalidArgument ='15'的值对'index'无效。
它发生在RefreshTest在这条线: pictureBox1.Image = imageList1.Images[i];
我想,当我点击关闭butom程序完成RefreshTest因为是在内存和最终运行它发现的一切,但我不知道如何避免它。
您的图像集没有15幅图像,所以它击中OutOfRangeException。即使关闭表单,RefreshTest()仍然会在关闭之前完成。您可以调用FinishTest()方法而不会破坏代码,因此一旦FinishTest()完成,代码将完成RefreshTest()方法的其余部分。因为您使用的是全局变量,所以您必须将i和j变量设置为0.您是否看到问题? –
请添加像I和J这样的所有变量,但它们从未定义。解释你的变量而不仅仅是字母是一种更好的做法。像ImageCounter而不是i。 –
我已经添加它了。 – Pedro