我正在做一個簡單的測試程序,但是當我關閉窗體的關閉按鈕時(窗口右上方的正常按鈕,而不是按鈕)我自己)。關閉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