我有一个表,与司机的ID,姓名,等处理SQL的ExecuteNonQuery错误C#
我写了从一个文本框获得驾驶员的ID,并执行使用ExecuteNonQuery();
方法查询的方法。它检索驱动程序的数据。但是如果用户输入了一个不在表格中的ID,Winforms就会关闭。
我想改为显示一个MessageBox或类似的错误,如ID不存在。我怎样才能做到这一点?
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";
}
}
我想这种方式这表明我的意见河畔它partialy工作。但我有一个按钮,多次调用该方法“comandoSQLtxtBox”!所以我得到almos 15 MessageBox。我试着把this.close();在捕获但它不炒锅(给出错误)。 ANY小费?
来电:
//------------------------------------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);
你能提供一个代码吗? – Usman