invalid attempt to read when reader is closed

0

I'm having problems with an exception thrown at me by an application I'm developing with c # and MySQL. The exception is: "invalid attempt to read when reader is closed." and it happens to me when I enter for the second time a code that I should look for in a table of my bd.

This exception happens when I enter a code that is not registered in the bd or if it is already repeated, but if it is not registered in the bd it should not save it and it does, and if it is repeated, it updates two fields according to the code that was entered (thing that should do) but also throws me this exception in the method camion_shown. My code is as follows, I use two Forms, if you need to explain me more with my code please comment, thank you very much.

Form1 (Not much to see)

namespace BasculaCañera
{
    public partial class Form1 : Form
    {


        private void button1_Click(object sender, EventArgs e)
        {
            Form2 fr2 = new Form2();
            fr2.Show();
        }

        public String texto, codigo, aux, cuerpo = "";
        public char cabeza;




        public Form1()
        {
            InitializeComponent();

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter)) //Si el textbox detecta un enter, entra a esta condición.
            {



                texto = textBox1.Text;
                codigo = texto;
                textBox2.Text = codigo;
                textBox1.Text = "";
                cuerpo = "";
                var arreglo = codigo.ToCharArray(); //convierte la cadena en un arreglo de carácteres
                cabeza = arreglo[0];               //para guardar el primer carácter en una variable.


                for(int i = 1; i < arreglo.Length; i++)
                {
                    aux = Char.ToString(arreglo[i]);
                    cuerpo += aux;

                }  //Arreglo para juntar denuevo todo el cuerpo de la palabra(Sin la cabeza).

                if(cabeza=='B')
                {
                    if (cuerpo.Length == 6)
                    {
                        textBox3.Text = Char.ToString(cabeza);
                        textBox4.Text = cuerpo;
                        label1.Text = "Alzadora";
                        label3.Text = cuerpo;

                    }


                    if (cuerpo.Length != 6)
                    {
                        MessageBox.Show("Codigo incorrecto");
                    }
                }

                if (cabeza == 'C')
                {
                    if (cuerpo.Length == 6)
                    {
                        textBox3.Text = Char.ToString(cabeza);
                        textBox4.Text = cuerpo;
                        label1.Text = "Cabo";
                        label3.Text = cuerpo;
                    }
                    if (cuerpo.Length != 6)
                    {
                        MessageBox.Show("Codigo incorrecto");

                    }
                }

                if (cabeza == 'D')
                {
                    if (cuerpo.Length == 7)
                    {
                        textBox3.Text = Char.ToString(cabeza);
                        textBox4.Text = cuerpo;
                        label1.Text = "Camion";
                        label3.Text = cuerpo;

                        Camion cam = new Camion(cuerpo, cabeza);


                            cam.Show();
                            Console.WriteLine(codigo);
                            Console.WriteLine(cabeza);
                            Console.WriteLine(cuerpo);


                    }



                    if (cuerpo.Length != 7)
                    {
                        MessageBox.Show("Codigo incorrecto"); Console.WriteLine(codigo);
                        Console.WriteLine(cabeza);
                        Console.WriteLine(cuerpo);
                    }
                }


                if (cabeza != 'B' && cabeza != 'C' && cabeza != 'D')
                {
                    MessageBox.Show("Codigo incorrecto");
                }










            }
        }


    }
}

Truck

namespace BasculaCañera
{
    public partial class Camion : Form
    {
        //192.168.120.49
        MySqlCommand Query = new MySqlCommand();
        MySqlCommand Query2 = new MySqlCommand();
        MySqlConnection Conexion;
        MySqlDataReader consultar;
        public static MySqlConnection cnx = new MySqlConnection("server = localhost; database=estetica; Uid=root; pwd=;");
        public string sql = "server=localhost; database=bascula; Uid=root; pwd=;";
        DataTable tmp = new DataTable();
        string getCuerpo;
        char getCabeza;


        public Camion(string Cuerpo, char Cabeza)
        {
            InitializeComponent();
            getCuerpo = Cuerpo;
            getCabeza = Cabeza;
        }

        private void Camion_Load(object sender, EventArgs e)
        {
            textBox1.Text = getCabeza + getCuerpo;
            try
            {
                string Codigo, Chofer, Camion, Placas;

                Conexion = new MySqlConnection();
                Conexion.ConnectionString = sql;
                Conexion.Open();
                Query.CommandText = "SELECT * FROM estetica.camion where Codigo='" + textBox1.Text + "';";
                Query.Connection = Conexion;
                consultar = Query.ExecuteReader();

                while (consultar.Read())
                {                  
                    Codigo = consultar.GetString(1);
                    Chofer = consultar.GetString(2);
                    Camion = consultar.GetString(3);
                    Placas = consultar.GetString(4);

                    if (consultar.HasRows)
                    {
                        textBox2.Text = Chofer;
                        textBox3.Text = Camion;
                        textBox4.Text = Placas;
                        Conexion.Close();


                    }
                    else
                    {
                        MessageBox.Show("El codigo no contiene información");
                        Conexion.Close();
                        this.Close();


                    }
                }

            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void Camion_Shown(object sender, EventArgs e)
        {

            Conexion = new MySqlConnection();
            Conexion.ConnectionString = sql;
            Conexion.Open();
            Query.CommandText = "select count(*) from bascula.camion where Codigo='" + getCabeza + getCuerpo + "';";
            Query.Connection = Conexion;
            consultar = Query.ExecuteReader();



            while (consultar.Read())
            {

                int count;
                count = consultar.GetInt32(0);

                if (count == 0)
                {
                    agregar();
                }
                else
                {
                    modificar();
                }




            }


        }

        public void modificar()
        {
            try
            {
                Conexion = new MySqlConnection();
                Conexion.ConnectionString = sql;
                Conexion.Open();
                Query.CommandText = "select count(*) from bascula.camion where Codigo='" + textBox1.Text + " and PesoSalida=0';";
                Query.Connection = Conexion;
                consultar = Query.ExecuteReader();

                while (consultar.Read())
                {
                    int count;
                    count = consultar.GetInt32(0);

                    if (count == 0)
                    {
                        agregarPesos();
                    }
                    else
                    {
                        MessageBox.Show("Este código ya no puede utilizarse");
                        this.Close();
                    }
                }
                Conexion.Close();
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void agregarPesos()
        {
            int maximo;
            Conexion = new MySqlConnection();
            Conexion.ConnectionString = sql;
            Conexion.Open();
            Query.CommandText = "SELECT PesoEntrada FROM bascula.camion where Codigo='" + getCabeza+getCuerpo + "';";
            Query.Connection = Conexion;
            consultar = Query.ExecuteReader();

            while (consultar.Read())
            {

                maximo = consultar.GetInt32(0);
                Random rnd = new Random();
                int pesoSalida = rnd.Next(50000, maximo);
                int pesoNeto = maximo - pesoSalida;

                MySqlDataAdapter msj = new MySqlDataAdapter("UPDATE 'bascula'.'camion' SET 'PesoSalida'='" + pesoSalida + " ', 'PesoNeto'='" + pesoNeto + "' WHERE 'Codigo'='" + getCabeza+getCuerpo + "';", cnx);
                try
                {
                    cnx.Open();
                    msj.Fill(tmp);
                    cnx.Close();

                }
                catch (Exception r)
                {
                    MessageBox.Show(r.Message);
                }
                finally { cnx.Close(); }


            }
            Conexion.Close();

        }

        public void agregar()
        {
            Random rnd = new Random();
            var PesoEntrada = rnd.Next(50000, 59000);

            bool cerrado = false;

            if (string.IsNullOrWhiteSpace(textBox2.Text) && string.IsNullOrWhiteSpace(textBox3.Text) && string.IsNullOrWhiteSpace(textBox4.Text))
            {
                cerrar();
                MessageBox.Show("Codigo no encontrado");
                cerrado = true;

            }

            if (string.IsNullOrWhiteSpace(textBox2.Text) && cerrado == false)
            {
                cerrar();
                MessageBox.Show("Chofer no encontrado");
                cerrado = true;


            }
            if (string.IsNullOrWhiteSpace(textBox3.Text) && cerrado == false)
            {
                cerrar();
                MessageBox.Show("Camion no encontrado");
                cerrado = true;

            }
            if (string.IsNullOrWhiteSpace(textBox4.Text) && cerrado == false)
            {
                cerrar();
                MessageBox.Show("Placas no encontradas");
                cerrado = true;

            }


            MySqlDataAdapter msj = new MySqlDataAdapter("INSERT INTO 'bascula'.'camion' ('Codigo', 'PesoEntrada', 'Chofer', 'Camion', 'Placas') VALUES ('" + getCabeza + getCuerpo + "', '" + PesoEntrada + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "');", cnx);
            try
            {
                cnx.Open();
                msj.Fill(tmp);
                cnx.Close();
                this.Close();

            }
            catch (Exception r)
            {
                MessageBox.Show(r.Message);
            }
            finally { cnx.Close(); }




        }

        private void cerrar()
        {
            this.Close();
        }
    }
}
    
asked by Erick Alg 29.09.2017 в 19:10
source

1 answer

0

I must comment that the code is quite unramaged, you have connection objects defined globally in the form and others define them in each method, as you are not sure you are not making the open() of a connection before executing the command

I would recommend that you program in layers, unless they are two layers, the data layer will handle the data and you will not have the ado.net code in the same form.

[WinForms] Editing Employees

in the article I explain how you should program this layer.

You also have to use parameters in the code, concatenating the values in the string is not a good practice.

The problem occurs in Camion_Shown since you are invoking modificar() , but in mabs methods you use the same global command and reader, so if in modifica() perform Close() you are closing the same object

private string connstring = "server=localhost; database=bascula; Uid=root; pwd=;";

private void Camion_Shown(object sender, EventArgs e)
{

    using(MySqlConnection conn = new MySqlConnection(connstring))
    {
        conn.Open();

        string query = "select count(*) from bascula.camion where Codigo= ?codigo";
        MySqlCommand cmd = new MySqlCommand(query, conn);
        cmd.Parameters.AddWithValue("?codigo", getCabeza + getCuerpo);

        MySqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            int count = consultar.GetInt32(0);

            if (count == 0)
            {
                agregar();
            }
            else
            {
                modificar();
            }
        }

    }   

}

public void modificar()
{
    try
    {

        using(MySqlConnection conn = new MySqlConnection(connstring))
        {
            conn.Open();

            string query = "select count(*) from bascula.camion where Codigo= ?codigo and PesoSalida=0";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            cmd.Parameters.AddWithValue("?codigo", textBox1.Text);

            MySqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                int count = consultar.GetInt32(0);

                if (count == 0)
                {
                    agregarPesos();
                }
                else
                {
                    MessageBox.Show("Este código ya no puede utilizarse");
                    this.Close();
                }
            }

        }

    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Analyze the structure of this example that adapts based on your code, apply it in agregarPesos()

Always define the objects of connection to the db locally, remove those that are global to the form

I did not want to change the code so much, but if in the query you define a COUNT you can use ExecuteScalar() , like in this example

private void Camion_Shown(object sender, EventArgs e)
{

    using(MySqlConnection conn = new MySqlConnection(connstring))
    {
        conn.Open();

        string query = "select count(*) from bascula.camion where Codigo= ?codigo";
        MySqlCommand cmd = new MySqlCommand(query, conn);
        cmd.Parameters.AddWithValue("?codigo", getCabeza + getCuerpo);

        int count = Convert.ToInt32(cmd.ExecuteScalar());

        if (count == 0)
        {
            agregar();
        }
        else
        {
            modificar();
        }
    }   

}
    
answered by 29.09.2017 / 20:09
source