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);
Put your query in a try/catch block, and show the MessageBox in the catch. Something like, e.g.:
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);
}
Take your data in one Datatable and if that particular datatable has the data then it will be shown, otherwise you can use:
MessageBox.Show("Your Message");
After this you can close the winform by:
this.close();
Related
So I was trying to add the firstName and lastName in my combobox in my voting system project for our school. I'm getting an error which is getString is not possible to use in this type of syntax. Is there any other way to add this values into 1 single slot to my combo box?
using (MySqlConnection con = new MySqlConnection(connection))
{
//Opening of Connection
con.Open();
MySqlDataReader dataReader;
//FOR PRESIDENT
using (MySqlCommand votePresident = new MySqlCommand(displayPresident, con))
{
try
{
int votePres = 0;
votePres = votePresident.ExecuteNonQuery();
dataReader = votePresident.ExecuteReader();
//Loop to read the Data
while (dataReader.Read())
{
String rollPres = dataReader.GetString("firstName","lastName");
presidentbox.Items.Add(rollPres);
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to Vote" + ex);
}
}
Error Shows this
Problem solved while searching the internet
I used this to connect the 2 strings
while (dataReader.Read())
{
String rollPresf = dataReader.GetString("firstName");
String rollPresl = dataReader.GetString("lastName");
presidentbox.Items.Add(rollPresf + " " + rollPresl);
}
I am using the same button "Save" to update a table called AnalysisExperiments and also to insert data into a table called "Analysis". however the update is not working. Here is the code:
#region Insert Data into Analysis Table
if (checkIfRepeatedJobNumber(tbJobNumber.Text.Trim()))
{
MessageBox.Show("Job Number is already exist.", "Repeated Data");
return;
}
string query = "insert into Analysis (ID, WellName, EstimatedStartDate, SOWComments, ProgressComments, Field, FocalPoint, StudyCompleted, Company, ReservoirPressure, ReservoirTemp, SelectedSamples) " +
"values (#ID, #WellName, #SamplingDate, #SOWComments, #ProgressComments, #Field, #FocalPoint, #StudyCompleted, #Company, #ReservoirPressure, #ReservoirTemp, #SelectedSamples)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("#ID", tbJobNumber.Text);
cmd.Parameters.AddWithValue("#WellName", tbWellName.Text);
cmd.Parameters.AddWithValue("#SamplingDate", dtpSamplingDate.Text);
cmd.Parameters.AddWithValue("#SOWComments", tbSOW_Comments.Text);
cmd.Parameters.AddWithValue("#ProgressComments", tbProgressComments.Text);
cmd.Parameters.AddWithValue("#Field", tbFieldName.Text);
cmd.Parameters.AddWithValue("#FocalPoint", tbFocalName.Text);
if (radYes.Checked)
cmd.Parameters.AddWithValue("#StudyCompleted", "Yes");
else
cmd.Parameters.AddWithValue("#StudyCompleted", "No");
cmd.Parameters.AddWithValue("#Company", tbCompany.Text);
cmd.Parameters.AddWithValue("#ReservoirPressure", tbReservoirPressure.Text);
cmd.Parameters.AddWithValue("#ReservoirTemp", tbReservoirTemp.Text);
cmd.Parameters.AddWithValue("##SelectedSamples", tbSelectedSamples.Text);
try
{
conn.Open();
int j = cmd.ExecuteNonQuery();
if (j == 1)
{
MessageBox.Show("Done");
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
#endregion
#region update analysis Exp but still no working
#region Update database
try
{ int k = 0;
OleDbDataAdapter da;
da = new OleDbDataAdapter("select* from [AnalysisExperiments]", conn);
string ExpQuery = "update AnalysisExperiments set SampleNumber = #SampleNumber, Status = #Status where ID = '" + tbJobNumber.Text + "' and Experiment = '";
foreach (DataGridViewRow row in dgvExperiments.Rows)
{
ExpQuery += row.Cells["Experiment"].Value.ToString() + "'";
OleDbCommand updateCommand = new OleDbCommand(ExpQuery, conn);
updateCommand.Parameters.Add("#SampleNumber", OleDbType.VarWChar);
MessageBox.Show(row.Cells["SampleNumber"].Value.ToString() + " | " + row.Cells["Status"].Value.ToString() + " | " + row.Cells["Experiment"].Value.ToString());
updateCommand.Parameters["#SampleNumber"].Value = row.Cells["SampleNumber"].Value.ToString();
updateCommand.Parameters.Add("#Status", OleDbType.Boolean);
updateCommand.Parameters["#Status"].Value = row.Cells["Status"].Value;
da.UpdateCommand = updateCommand;
conn.Open();
k = da.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
if (k == 1)
MessageBox.Show("Done");
else
{
MessageBox.Show("Nothing Updated!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
#endregion
knowing that the compiler skips the loop in the update region.
At the second loop the query syntax becomes invalid cause the += that concatenates the previous text with the new one
Dim newQuery = ExQuery + row.Cells["Experiment"].Value.ToString() + "'";
And then use the new string for the ExecuteNonQuery.
Still this approach has many problems. You should separate this code in different methods and use parameters also for the last value
Have you tried to debug the foreach line to see if there are any rows in your dgvExperiments and if they are of type (or subtype of) DataGridViewRow ?
I'm having problems retrieving values from the SQL database in visual studio. I have columns(GuestName, GuestPassportNo, GuestCountry, RoomID, HotelPackageID) in the GUEST table where HotelPackageID contains a NULL value while the rest are with values. I'm always thrown into the else statement(no record found) when HotelPackageID is NULL. Anyone have a solution, please? Here is my code:
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT Guest.GuestPassportNo,
Guest.GuestName,
Guest.GuestCountry,
Guest.RoomID,
Room.RoomDescription,
Room.RoomPrice,
HotelPackages.PackageName,
HotelPackages.PackagePrice ";
strCommandText += " FROM Guest, Room, HotelPackages";
strCommandText +=" WHERE Guest.RoomID=Room.RoomID
AND Guest.GuestPassportNo=#guestpno
AND HotelPackages.PackageID=Guest.HotelPackageID
AND Guest.GuestCountry=#guestcountry;
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#guestpno", txtPassportNo.Text);
cmd.Parameters.AddWithValue("#guestcountry", txtGuestCountry.Text);
try
{
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
txtGuestName.Text = reader["GuestName"].ToString();
txtRoomDescription.Text = reader["RoomDescription"].ToString();
txtRoomPrice.Text = reader["RoomPrice"].ToString();
txtHotelPackage.Text = reader["PackageName"].ToString();
txtPackagePrice.Text = reader["PackagePrice"].ToString();
MessageBox.Show("Guest Record Found!");
}
else
{
Messagebox.Show("No record Found");
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
finally
{
myConnect.Close();
}
You need to change your query:
strCommandText +=" WHERE Guest.RoomID=Room.RoomID AND Guest.GuestPassportNo=#guestpno AND HotelPackages.PackageID=Guest.HotelPackageID AND Guest.GuestCountry=#guestcountry;
should be:
strCommandText +=" WHERE Guest.RoomID=Room.RoomID AND Guest.GuestPassportNo=#guestpno AND (HotelPackages.PackageID=Guest.HotelPackageID OR GUEST.HotelPackageID IS NULL) AND Guest.GuestCountry=#guestcountry;
Having problem reading a value from my table in mysql, is the index value i cant read the value back no matter what. all i get is the initialized value of 0 i dont get any error because it return 0, if i run the query in the database it get the correct value. i tried to use executeScalar() but with the same result .
MySqlConnection conn = new MySqlConnection(MyConString);
ulong ukey=0;
try
{
string sql_users2 = "SELECT `key` FROM `permuser` WHERE `user` = '" + myuser + "' AND `code` = '" + mycode + "'";
MySqlCommand cmdSel2 = new MySqlCommand(sql_users2, conn);
conn.Open();
MySqlDataReader dr2 = cmdSel2.ExecuteReader();
dr2.Read();
ukey = dr2.GetUInt64(dr2.GetOrdinal("key"));
// MessageBox.Show("Sorry " + myuser + " already have access to " + mycode + ",\nIf this is an extension, search for the user which key is " + ukey + " and edit the end date.", "Duplicate User Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
dr2.Close();
dr2.Dispose();
}
catch (MySqlException ex) //catch 2
{
MessageBox.Show("catch ukey\nCan't connect to database\n" + ex.ToString());
}
conn.Close();
conn.Dispose();
You are returning a single value from your query, so you could use directly ExecuteScalar instead of ExecuteReader. (the link point to the description for SqlServer, but it is the same for MySql)
An important question to never forget is the usage of parameters instead of string concatenation.
What happen if your myuser or mycode variables contain a single quote? You get wrong results or syntax errors.
Of course, the main problem is the Sql Injection attack to never understimate.
using(MySqlConnection conn = new MySqlConnection(MyConString))
{
ulong ukey=0;
try
{
string sql_users2 = "SELECT `key` FROM `permuser` WHERE `user` = #usr AND `code` = #code";
MySqlCommand cmdSel2 = new MySqlCommand(sql_users2, conn);
conn.Open();
cmdSel2.Parameters.AddWithValue("#usr", myuser);
cmdSel2.Parameters.AddWithValue("#code", mycode);
object result = cmdSel2.ExecuteScalar();
if(result != null)
ukey = Convert.ToUInt64(result);
}
catch (MySqlException ex) //catch 2
{
MessageBox.Show("catch ukey\nCan't connect to database\n" + ex.ToString());
}
}
also I am a bit perplexed about your usage of UInt64. What kind of datatype is stored in the key column?
way is many simply:
ukey = (uint)dr2[0];
I have a delete button syntax problem in c sharp
and I've made a syntax like this delete button
string conection = "Provider = Microsoft.Jet.OleDb.4.0;Data Source=Database.mdb";
try
{
int i = 0;
for (i = 0; i < dataGridView1.CurrentRow.Cells.Count; i++)
{
DataGridViewCell cell = dataGridView1.CurrentRow.Cells[i];
if (cell.Selected == true)
{
string sql = string.Format("DELETE * FROM mahasiswa WHERE " + i + " ");
OleDbConnection conn = new OleDbConnection(conection);
conn.Open();
dataGridView1.Rows.RemoveAt(i);
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.ToString());
}
but the code is syntax error in query, database records do not go to delete
how to code the query syntax is correct?
please help me
I created a database from microsoft access to the names and table names database.mdb supplier with columns id, name, address
primary key: id
Your sql syntax is wrong. It should be something like this:
string sql = string.Format("DELETE FROM mahasiswa WHERE id = {0}", i.ToString());