Retrieving null value and other values from sql database to textbox - c#

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;

Related

Encountering a System.IndexOutOfRangeException: when trying to display data from two tables in a database

I am writing a form application. User inputs his name, email, address etc into text boxes as if he was ordering a package. If the user has already made an order once I want to make it possible for the user to enter his email into the text box and based on his email fill out all the other personal information needed for the package.
The trouble I am having is that his data is in two different tables. The data which is in customer table (his first and last name) I have successfully retrieved, but the data in the table address I don't know how to get.
Here is the code:
{
try
{
var connection = getConnection();
var command = new SqlCommand
{
Connection = connection,
CommandText = "SELECT * FROM Customer WHERE Email = #Email"
};
command.Parameters.Clear();
command.Parameters.AddWithValue("#Email", mailBox.Text);
connection.Open();
reader = command.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
fnameBox.Text = reader["fname"].ToString();
lnameBox.Text = reader["lname"].ToString();
command.CommandText = "SELECT * FROM address WHERE customerID= "+ reader["customerID"].ToString();
stateBox.Text = reader["state"].ToString(); //part where the error happens
cityBox.Text = reader["city"].ToString();
addressBox.Text = reader["address"].ToString();
zipBox.Text = reader["zip"].ToString();
int result = command.ExecuteNonQuery();
connection.Close();
if (result > 0)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Error");
}
}
else
{
MessageBox.Show("E-mail entered doesn't exist");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} ```
Look into using something like EF in future, will clean such things up, but appreciate this is probably not feasible for what you're doing here.
You should get related data from multiple tables via SQL Joins (look into LEFT JOIN and INNER JOIN)
Your problem is caused by the result set not having a state field, which in turn is caused by your not actually executing your SELECT * FROM address query - you are setting the command text but doing nothing further. You need to create another DataReader for the second query and read those results.
Overall there's a lot of stuff to improve, but you're clearly at an early state in learning this so that's fine for now....
you didn't finish to read the first result and after this trying to get the second one
command.Parameters.Clear();
command.Parameters.AddWithValue("#Email", mailBox.Text);
var customerID=0;
var success=false;
connection.Open();
var reader1 = command.ExecuteReader();
if (reader1.Read())
{
sucess=true;
fnameBox.Text = reader1["fname"].ToString();
lnameBox.Text = reader1["lname"].ToString();
customerID= Convert.ToInt32( reader1["customerID"].ToString());
reader1.Close();
}
if( sucess)
{
command.CommandText = "SELECT * FROM address WHERE customerID = #CustomerID";
command.Parameters.Clear();
command.Parameters.AddWithValue("#CustomerID", customerID);
var reader2 = command.ExecuteReader();
sucess=false;
if (reader2.Read())
{
sucess=true;
stateBox.Text = reader2["state"].ToString();
cityBox.Text = reader2["city"].ToString();
addressBox.Text = reader2["address"].ToString();
zipBox.Text = reader2["zip"].ToString();
reader2.Close();
}
if (success)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(" address select Error");
}
}
else
{
MessageBox.Show("E-mail entered doesn't exist");
}
connection.Close();

How to check if user in mysql database exists (in c#)

So I know this is a often asked question but I want to check if the username is already taken in the database using c#. I tried this:
MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE(name = '" + tb1.Text + "');");
cmd2.Connection = connect;
connect.Open();
string unt = "";
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
unt= dr.GetString("name");
}
dr.Close();
}
catch (Exception ex)
{
errorbox.Content = ex.Message;
}
finally
{
connect.Close();
}
if(unt == "" || unt == "0") {
continuel = false;
tb2.Text = "User " +tb1.Text+ " doesn't exist!";
Popup1.IsOpen = true;
}
Its a WPF project and the variable 'continuel' is set to true by default. The code doesn't recognize if a user doesn't exist.
First off your code is vulnerable to sql inject, you should never concatenate values into a query. secondly you can do a count and execute a scalar. Not I stripped down your code a little you'll have to add error handling back.
bool userExists = false;
private String sql = "SELECT COUNT(*) FROM tableName WHERE name = #usernameparam;";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("#usernameparam", tb1.Text.Trim());
int userCount = Convert.ToInt32(m.ExecuteScalar());
if(userCount>0)
{
userExists = true;
}
//use userExists variable to evaluate if user exists

Handle SQL ExecuteNonQuery errors C#

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

How to autofill a radio_button, a few combo_boxes, many text_boxes, and a calendar FROM a combo_box selection

I am creating a tool that will allow a Human Resource employee to input various information about a new employee into an access database(for academic purposes). So far I have the layout set-up (as you will be able to see shortly), validation is in a place, and a dataGridView gets populated by using an Access Database I created. Then I have 3 buttons, Submit (Insert), Update and Delete.
PS: I know that the table I am trying to update is huge, but that's what our team decided to do.
Image of my layout:
Human Resource employee tool
The submit and delete works, BUT the update only works if all of the fields are filled with data. The code I wrote tries to update all the fields WHERE the EMPLOYEE_ID equals the value that's selected on the combo_box, so if I try to update only one field I get an error saying "No value given for one or more required parameters". I think that by auto-filling all the field on the left when a value from a combo_box is selected will fix my problem. The thing is that I have no idea on how to accomplish this. Any help would be appreciate it!!
UPDATE STATEMENT.
private void cmdModify_Click(object sender, EventArgs e)
{
//Setting up Connection String
string connectionString = GetConnectionString();
string SqlString = "UPDATE Employee SET FIRST_NAME = #FirstName , LAST_NAME= #LastName, MIDDLE_NAME = #MiddleName, DATE_HIRED =#DateHired, WAGE_TYPE =#WageType, WAGE = #Wage, GENDER =#Gender, MARTIAL_STATUS =#MartialStatus, UNIT_NUMBER =#UnitNumber, STREET_NUMBER =#StreetNumber, STREET_NAME =#StreetName, CITY =#City, PROVINCE =#Province, POSTAL_CODE =#PostalCode, HOME_NUMBER =#HomeNumber, CELL_NUMBER =#CellNumber, JOB_TITTLE =#JobTittle, END_DATE=7/24/2013, DPT_NAME =#Department, NOTES =#Notes WHERE [EMPLOYEE_ID] = #EMPLOYEE_ID";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFname.Text);
cmd.Parameters.AddWithValue("LastName", txtLname.Text);
cmd.Parameters.AddWithValue("MiddleName", txtMname.Text);
cmd.Parameters.AddWithValue("DateHired", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("WageType", cmbType.SelectedItem);
cmd.Parameters.AddWithValue("Wage", txtWage.Text);
if (rbMale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbMale.Text);
}
else if (rbFemale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbFemale.Text);
}
cmd.Parameters.AddWithValue("MartialStatus", cmbStatus.SelectedItem);
cmd.Parameters.AddWithValue("UnitNumber", txtUnit.Text);
cmd.Parameters.AddWithValue("StreetNumber", txtStreetNo.Text);
cmd.Parameters.AddWithValue("StreetName", txtStreet.Text);
cmd.Parameters.AddWithValue("City", txtCity.Text);
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
cmd.Parameters.AddWithValue("PostalCode", txtPostal.Text);
cmd.Parameters.AddWithValue("HomeNumber", txtHphone.Text);
cmd.Parameters.AddWithValue("CellNumber", txtCphone.Text);
cmd.Parameters.AddWithValue("JobTittle", cmbJobTitle.SelectedItem);
cmd.Parameters.AddWithValue("Department", cmbDepartment.SelectedItem);
cmd.Parameters.AddWithValue("Notes", txtNotes.Text);
cmd.Parameters.AddWithValue("EMPLOYEE_ID", comboBox1.SelectedValue);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was added to the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
INSERT STATEMENT.
private void Insert_Data()
{
string connectionString = GetConnectionString();
string SqlString = "INSERT INTO Employee (FIRST_NAME, LAST_NAME, MIDDLE_NAME, DATE_HIRED, WAGE_TYPE, WAGE, GENDER, MARTIAL_STATUS,UNIT_NUMBER, STREET_NUMBER, STREET_NAME, CITY ,PROVINCE, POSTAL_CODE, HOME_NUMBER, CELL_NUMBER, JOB_TITTLE, END_DATE, DPT_NAME, NOTES) VALUES (#FirstName,#LastName,#MiddleName,#DateHired,#WageType,#Wage,#Gender,#MartialStatus,#UnitNumber,#StreetNumber,#StreetName,#City,#Province,#PostalCode,#HomeNumber,#CellNumber,#JobTittle,7/24/2013,#Department,#Notes)";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFname.Text);
cmd.Parameters.AddWithValue("LastName", txtLname.Text);
cmd.Parameters.AddWithValue("MiddleName", txtMname.Text);
cmd.Parameters.AddWithValue("DateHired", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("WageType", cmbType.SelectedItem);
cmd.Parameters.AddWithValue("Wage", txtWage.Text);
if (rbMale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender",rbMale.Text);
}
else if (rbFemale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbFemale.Text);
}
cmd.Parameters.AddWithValue("MartialStatus", cmbStatus.SelectedItem);
cmd.Parameters.AddWithValue("UnitNumber", txtUnit.Text);
cmd.Parameters.AddWithValue("StreetNumber", txtStreetNo.Text);
cmd.Parameters.AddWithValue("StreetName", txtStreet.Text);
cmd.Parameters.AddWithValue("City", txtCity.Text);
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
cmd.Parameters.AddWithValue("PostalCode", txtPostal.Text);
cmd.Parameters.AddWithValue("HomeNumber", txtHphone.Text);
cmd.Parameters.AddWithValue("CellNumber", txtCphone.Text);
cmd.Parameters.AddWithValue("JobTittle", cmbJobTitle.SelectedItem);
cmd.Parameters.AddWithValue("Department", cmbDepartment.SelectedItem);
cmd.Parameters.AddWithValue("Notes", txtNotes.Text);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was added to the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
DELETE STATEMENT
private void cmdDelete_Click_1(object sender, EventArgs e)
{
//Setting up Connection String
string connectionString = GetConnectionString();
string SqlString = "DELETE * FROM Employee WHERE [EMPLOYEE_ID] = #EMPLOYEE_ID ";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("EMPLOYEE_ID", comboBox1.SelectedValue);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was deleted from the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
You are getting this error because the AddWithValue method is adding null to the Parameters collection. What you need is for it to add DBNull instead.
cmd.Parameters.AddWithValue("FirstName", txtFname.Text ?? DBNull.Value);
Those SelectedItem values might cause you problems too if they are complex types:
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
You might have to specify a property on the instance to make it work
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem.MyIdProperty);

Delete record database from DataGridview cell

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

Categories

Resources