Search code examples
c#ms-accessoledbwindows-forms-designersqldatareader

exam math from data using OLEDB


I'm trying to make an exam form. It is suppose to take a question from different tables in my file, and by clicking Q1button to check the answer and print a suitable message. In addition, it is suppose to ask the user 8 questions, and update the answer (if it was answered correctly) in counterCorrectAns. By clicking Q1button it is updating the textboxes in random question from specific table.

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();
    }

}

The error that I get :COM object that has been separated from its underlying RCW cannot be used. in the line with //**// in its beginning.


Solution

  • The using already manage the connection.close().

    On MSDN documentation, they don't put connection.close() if they wrap their code in using instruction.

    What is happening is that the using tries to close a connection that you already closed.

    However, reader should be closed before the end of the using block