1

我正在尝试制作考试表格。假设从我文件中的不同表格中提取问题,然后单击Q1button以检查答案并打印合适的消息。此外,假设向用户提出 8 个问题,并更新答案(如果答案正确)counterCorrectAns。通过单击Q1button它来更新特定表中随机问题的文本框。

private int randomQues=0,number=1,counterCorrectAns=0;
private string correctAns = "";

void SetQues1Box(int number)
{
    string whatTake="",fromWhere="",autoNum="";

    from.Text =""+ number;
    to.Text = "" + 8;
    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\hodaya\\Desktop\\Project.accdb";

    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        switch (number)
        {
            case 1: whatTake = "misHQueA, mishAnsA"; fromWhere = "mishvaotA"; autoNum = "mishAnum"; break;
            case 2: whatTake = "misHQueB, mishAnsB"; fromWhere = "mishvaotB"; autoNum = "mishBnum"; break;

        }
        string sql = "SELECT " + whatTake + " FROM " + fromWhere + " WHERE " + autoNum + "=?";

        Random r = new Random();
        randomQues=r.Next(1, 25);
        using (OleDbCommand command = new OleDbCommand(sql, connection))
        {
            connection.Open();
            command.Parameters.AddWithValue(autoNum, randomQues);
            OleDbDataReader reader = command.ExecuteReader();
            reader.Read();
            q1Box.Text = reader.GetString(0);
            correctAns = ("" + reader.GetInt32(1));
            connection.Close();
    //**// }
        }
    }
}

private void Q1Button_Click(object sender, EventArgs e)
{
    string exp;

    if (number <= 8)
    {
        if (ans1Box.Text == correctAns)
        {
            counterCorrectAns++;
            exp = "correct answer";
        }
        else
            exp = "'wrong answer";
        MessageBox.Show(exp);
        number = number + 1;
        SetQues1Box(number);
    }
    else
    {
        if (counterCorrectAns >= 4)
            MessageBox.Show("your great");
        else
            MessageBox.Show("you are need more practice");
        this.Close();
    }

}

我得到的错误:COM object that has been separated from its underlying RCW cannot be used.在其开头的 //**// 行中。

4

1 回答 1

1

使用已经管理的connection.close().

connection.close()在 MSDN 文档中,如果他们将代码包装在 using 指令中,他们不会放。

正在发生的事情是 using 试图关闭您已经关闭的连接。

但是,reader应该在 using 块结束之前关闭

于 2012-04-26T13:35:00.923 回答