Prasetyo Jean
Prasetyo Jean

Reputation: 57

Why can't OpenConnection() be called twice in one method?

Why can't I call OpenConnection() twice in one method? When I call it this error appears:

The connection is already open.

I call it twice in SelectDisPatient() and Count(). See my code at for (int index = 0; index < Count(); index++)

This method SelectDisPatient:

public void SelectDisPatient(FrmVIRGO frm)
{
   string query = "SELECT id_pasien FROM tb_patient_information ";
   if (this.OpenConnection() == true)
   { //Create Command
      MySqlCommand cmd = new MySqlCommand(query, connection);
      //Create a data reader and Execute the command
      MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
      if (dataReader.HasRows)
      {
         for (int index = 0; index < Count(); index++)
         dataReader.Read();
         frm.tbName.Text = dataReader[0].ToString(); 
      } 
         //close Data Reader
         dataReader.Close();

         //close Connection
         this.CloseConnection();

    }
 }

This Count() method:

public int Count()
{
   string query = "SELECT Count(*) FROM tb_patient_information";
   int Count = -1;

   //Open Connection
   if (this.OpenConnection() == true)
   {
      //Create Mysql Command
      MySqlCommand cmd = new MySqlCommand(query, connection);

      //ExecuteScalar will return one value
      Count = int.Parse(cmd.ExecuteScalar()+"");

      //close Connection
      this.CloseConnection();

      return Count;
    }
    else
    {
       return Count;
    }
 }

But when I remove (this.OpenConnection() == true) in the Count() method it says I need to close the connection.

Upvotes: 1

Views: 937

Answers (1)

Damith
Damith

Reputation: 63065

Try:

public void SelectDisPatient(FrmVIRGO frm)
{
   int count =  Count();
   string query = "SELECT id_pasien FROM tb_patient_information ";
   if (this.OpenConnection() == true)
   { //Create Command
      MySqlCommand cmd = new MySqlCommand(query, connection);
      //Create a data reader and Execute the command
      MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
      if (dataReader.HasRows)
      {
         for (int index = 0; index < count ; index++)
         dataReader.Read();
         frm.tbName.Text = dataReader[0].ToString(); 
      } 
      //close Data Reader
      dataReader.Close();

      //close Connection
      this.CloseConnection();

    }
 }

Upvotes: 2

Related Questions