I have a table with driver's ID, name, surname, etc.
I wrote a method that gets the driver's ID from a textbox and executes a query using the ExecuteNonQuery(); method. It retrieves the driver's data. But if the user enters an ID which isn't in the table, the Winforms get closed.
I'd like to instead show a MessageBox or something similar appear such as an error that the ID doesn't exist. How can I do that?
EDDIT
public string comandoSQLtxtBox(string comando) { string datosConexion = "Data Source=JNATARIO-PC;Initial Catalog= viajesDB;Integrated Security=True;"; try { using (SqlConnection con = new SqlConnection(datosConexion)) { con.Open(); SqlCommand comandoCreartabla = new SqlCommand(comando, con); object scalarobject; scalarobject = comandoCreartabla.ExecuteScalar(); con.Close(); return scalarobject.ToString(); } } catch { MessageBox.Show("Ocurrio un error!"); return "0"; } } I tried that way which suggested me in comments nad it partialy worked. But I've a Button that call that method "comandoSQLtxtBox" many times!, so i get almos 15 MessageBox. I tried putting this.close(); in catch but it doesn't wok (gives error). ANy tip?
THE CALLS:
//------------------------------------DATOS CHOFER----------------------------------------- //ID chof string Id_chofer = sqlTools.comandoSQLtxtBox("SELECT id_chofer FROM viajes WHERE id_viaje=" + Id_viaje); boxIDChofViajeCurso.Text = Id_chofer; //Nombre chof boxNombreChofCurso.Text = sqlTools.comandoSQLtxtBox("SELECT nombre FROM choferes WHERE id_chofer=" + Id_chofer); //Apellido chof boxApellChofCurso.Text = sqlTools.comandoSQLtxtBox("SELECT apellido FROM choferes WHERE id_chofer=" + Id_chofer); //Telefono boxTlfChofCurso.Text = sqlTools.comandoSQLtxtBox("SELECT telefono FROM choferes WHERE id_chofer=" + Id_chofer); //Comentarios boxRichComChofCurso.Text = sqlTools.comandoSQLtxtBox("SELECT comentarios_chofer FROM choferes WHERE id_chofer=" + Id_chofer); //--------------------------------------DATOS AUTO------------------------------------------- //ID auto string Id_auto = sqlTools.comandoSQLtxtBox("SELECT id_auto FROM viajes WHERE id_viaje=" + Id_viaje); boxIDAutoCurso.Text = Id_auto; //Marca boxMarcaCurso.Text = sqlTools.comandoSQLtxtBox("SELECT marca FROM autos WHERE id_auto=" + Id_auto); //Modelo boxModeloCurso.Text = sqlTools.comandoSQLtxtBox("SELECT modelo FROM autos WHERE id_auto=" + Id_auto); //Patente boxPatenteCurso.Text = sqlTools.comandoSQLtxtBox("SELECT patente FROM autos WHERE id_auto=" + Id_auto); //Año boxAnAutoCurso.Text = sqlTools.comandoSQLtxtBox("SELECT año FROM autos WHERE id_auto=" + Id_auto); //Comentarios boxRichComAutoCurso.Text = sqlTools.comandoSQLtxtBox("SELECT comentarios_auto FROM autos WHERE id_auto=" + Id_auto);