我有一个表,里面有司机的ID,名字,姓氏等。
我编写了一个方法,该方法从文本框中获取驱动程序的ID,并使用ExecuteNonQuery();方法执行查询。它检索驱动程序的数据。但是如果用户输入的ID不在表中,Winforms就会关闭。
相反,我希望显示一个MessageBox或类似的内容,例如ID不存在的错误。我该怎么做呢?
编辑
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";
}
}我尝试过这种方式,它在评论中建议我,但它部分起作用了。但是我有一个可以多次调用该方法"comandoSQLtxtBox“的按钮,所以我得到了almos 15 MessageBox。我尝试将this.close();放在catch中,但它不工作(给出错误)。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);发布于 2017-02-11 11:29:47
将查询放在try/catch块中,并在catch中显示MessageBox。像这样,例如:
try
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
MessageBox.Show("An error occurred: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}发布于 2017-02-11 12:08:14
将您的数据放在一个Datatable中,如果该特定的datatable包含该数据,则会显示该数据,否则您可以使用:
MessageBox.Show("Your Message");在此之后,您可以通过以下方式关闭winform:
this.close();https://stackoverflow.com/questions/42171665
复制相似问题