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