i have
if (Text == "Add Client") // TEXT IS THE FORM.TEXT
{
newClient = new Client();
stateList = StateDB.GetStateList();
stateComboBox.DataSource = stateList;
clientBindingSource.Clear();
clientBindingSource.Add(newClient);
}
and this is my properties
and here is insert statement
SqlConnection connection = PRG299DB.GetConnection();
string insertStatement =
"INSERT INTO Client " +
"(FirstName, LastName, BirthDate, StreetName, " +
"City, State, ZipCode, CellPhone) " +
"VALUES (#FirstName, #LastName, #BirthDate, #StreetName, " +
"#City, #State, #ZipCode, #CellPhone);";
SqlCommand insertCommand = new SqlCommand(insertStatement,
connection);
insertCommand.Parameters.AddWithValue("#FirstName",
client.FirstName);
insertCommand.Parameters.AddWithValue("#LastName", client.LastName);
insertCommand.Parameters.AddWithValue("#BirthDate", client.BirthDate);
insertCommand.Parameters["#BirthDate"].SqlDbType = SqlDbType.DateTime;
insertCommand.Parameters.AddWithValue("#StreetName", client.StreetName);
insertCommand.Parameters.AddWithValue("#City", client.City );
insertCommand.Parameters.AddWithValue("#State", client.State);
insertCommand.Parameters.AddWithValue("#ZipCode", client.ZipCode);
if (client.CellPhone == null)
insertCommand.Parameters.AddWithValue("#CellPhone", DBNull.Value);
else
insertCommand.Parameters.AddWithValue("#CellPhone", client.CellPhone);
try
{
connection.Open();
insertCommand.ExecuteNonQuery();
string selectStatement =
"SELECT IDENT_CURRENT('Client') FROM Client";
SqlCommand selectCommand = new SqlCommand(selectStatement, connection);
int vendorID = Convert.ToInt32(selectCommand.ExecuteScalar());
return vendorID;
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
And the update statement
SqlConnection connection = PRG299DB.GetConnection();
string updateStatement =
"UPDATE Client SET " +
"FirstName = #NewFirstName, " +
"LastName = #NewLastName, " +
"BirthDate = #NewBirthDate, " +
"StreetName = #NewStreetName, " +
"City = #NewCity, " +
"State = #NewState, " +
"ZipCode = #NewZipCode, " +
"CellPhone = #NewCellPhone " +
"WHERE ClientID = #OldClientID " +
"AND FirstName = #OldFirstName " +
"AND LastName = #OldLastName " +
"AND Birthdate = #OldBirthDate " +
"AND StreetName = #OldStreetName " +
"AND City = #OldCity " +
"AND State = #OldState " +
"AND ZipCode = #OldZipCode " +
"AND (CellPhone = #OldCellPhone " +
"OR CellPhone IS NULL AND #OldCellPhone IS NULL)";
SqlCommand updateCommand = new SqlCommand(updateStatement, connection);
updateCommand.Parameters.AddWithValue("#NewFirstName", newClient.FirstName);
updateCommand.Parameters.AddWithValue("#NewLastName", newClient.LastName);
updateCommand.Parameters.AddWithValue("#NewBirthDate", newClient.BirthDate);
updateCommand.Parameters.AddWithValue("#NewStreetName", newClient.StreetName);
updateCommand.Parameters.AddWithValue("#NewCity", newClient.City);
updateCommand.Parameters.AddWithValue("#NewState", newClient.State);
updateCommand.Parameters.AddWithValue("#NewZipCode", newClient.ZipCode);
if (newClient.CellPhone == "")
updateCommand.Parameters.AddWithValue("#NewCellPhone", DBNull.Value);
else
updateCommand.Parameters.AddWithValue("#NewCellPhone", newClient.CellPhone);
updateCommand.Parameters.AddWithValue("#OldClientID", oldClient.ClientID);
updateCommand.Parameters.AddWithValue("#OldFirstName", oldClient.FirstName);
updateCommand.Parameters.AddWithValue("#OldLastName", oldClient.LastName);
updateCommand.Parameters.AddWithValue("#OldBirthDate", oldClient.BirthDate);
updateCommand.Parameters.AddWithValue("#OldStreetName", oldClient.StreetName);
updateCommand.Parameters.AddWithValue("#OldCity", oldClient.City);
updateCommand.Parameters.AddWithValue("#OldState", oldClient.State);
updateCommand.Parameters.AddWithValue("#OldZipCode", oldClient.ZipCode);
if (oldClient.CellPhone == "")
updateCommand.Parameters.AddWithValue("#OldCellPhone", DBNull.Value);
else
updateCommand.Parameters.AddWithValue("#OldCellPhone", oldClient.CellPhone);
try
{
connection.Open();
int count = updateCommand.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
i want to be able to have a display value of stateName and the selected value to be stateCode
for example: stateName: South Carolina and stateCode :sc
the error is that when i click the save. It don't save it to the database with the selected value :"sc" it saves with the display value "South Carolina"
i will really appreciate any hints or tips thanks in advance
if you need more code refer to this link
https://github.com/andakap99/ProjectPRG299DB/blob/master/WindowsFormsApplication1/frmAUI.cs
i needed to add a selected index changed event that looked like this
private void stateComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (newClient != null || newCompany != null || newSchool != null)
{
if (cliLVVisible)
{
newClient.State = (string)stateComboBox.SelectedValue;
}
else if (comLVVisible)
{
newCompany.State = (string)stateComboBox1.SelectedValue;
}
else if (schLVVisible)
{
newSchool.State= (string)stateComboBox2.SelectedValue;
}
}
}
Related
so my idea was once user will be loged in it will add +1 to the other table and online value in my mysql. I have done code like it's bellow. Once I have debug. I have inserted username and password but once I have press login button it says Error Connection. I am sure I have did something wrong in code but cant get it sort. So am trying to get help from you guys. Thanks
private void loginBtn_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
con.Open();
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
MySqlCommand newcmd = new MySqlCommand("UPDATE company SET online = online + 1 WHERE name = '" + row["company"].ToString() + "'");
try
{
newcmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
con.Close();
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
return;
}
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
For your question, you have connection error when you log in.
The error may be that there is already an open data reader associated with this connection
which must be closed, so close the data reader connection.
You could try the following code to get it.
private void btn_Submit_Click(object sender, EventArgs e)
{
conn.Open();
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteScalar();
MySqlDataReader row;
row = cmd.ExecuteReader();
string company=null;
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
company = row["company"].ToString();
MessageBox.Show(row["company"].ToString(), "Note", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
row.Close();
cmd.CommandText = "UPDATE company SET online = online + 1 WHERE name = '" + company + "'";
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
finally
{
conn.Close();
}
}
Result:
I am trying to save data into my database using the value stored in a session, however, the value must be of type int as stated in the database. how do I go about doing this? the code for the insertion is below.
protected void btnSave_outcome_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand sqlCmd = new SqlCommand("OutcomeCreateOrUpdate", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#outcomeID", (hfoutcomeID.Value == "" ? 0 : Convert.ToInt32(hfoutcomeID.Value)));
sqlCmd.Parameters.AddWithValue("#learning_activity", (ddlActivity.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
sqlCmd.Parameters.AddWithValue("#audience", (txtAudience1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#condition", (txtCondition1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#bloom_level", (ddlCategory1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#verb", (ddlVerb1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#product", (txtProduct2.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#degree", (txtDegree1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#statement", ("Given " + txtCondition1.Text.Trim() + ", " + txtAudience1.Text.Trim() + " Will be able to " + ddlVerb1.SelectedItem.Text + " " + txtProduct2.Text.Trim()+ " " + txtDegree1.Text.Trim() +"."));
//sqlCmd.Parameters.AddWithValue("#moduleID", (ddlmodules.SelectedIndex));
sqlCmd.ExecuteNonQuery();
con.Close();
//string objectiveID = hfobjectiveID.Value;
string outcomeID = hfoutcomeID.Value;
Clear();
if (outcomeID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
//FillGridView(); for outcomes
new_outcome.Visible = true;
}
and I created the session as follows
protected void redirect_outcomes_Click(object sender, EventArgs e)
{
Session["objectiveID"] = objectiveID.ToString();
//Session["module"] = ddlmodules.SelectedValue;
//Response.Redirect("learningoutcomes.aspx?MultiView1.ActiveIndex=" +2);
final_objective1.Text = "Given " + txtCondition.Text.Trim() + ", " + txtAudience.Text.Trim() + " Will be able to " + txtVerb.Text.Trim() + " " + txtProduct.Text.Trim() + " .";
MultiView1.Visible = false;
GoToAudience1.Visible = false;
MultiView2.ActiveViewIndex = 0;
}
Your code:-
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
My suggestion:-
if(Session["objectiveID"] != null)
{
sqlCmd.Parameters.AddWithValue("#objectiveID", Convert.ToInt32(Session["objectiveID"]));
}
No need to use try parse/parse because you are storing only integer value in session. So session have either empty or integer value.
this work but i want to display if value exist, so user can see the value username and last_update in each label based on each process_id but they have same request_id. this code only display username and last_update for the one that based on username login only.how i can do that ?
using(SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["MESTrans"].ConnectionString))
{
//bool exists = false;
int exists;
con.Open();
foreach (GridViewRow row in GridView2.Rows)
{
int req_id = Convert.ToInt32(GridView2.DataKeys[row.RowIndex].Values[0]);
using (SqlCommand cmd = new SqlCommand("select count(*) from [CutPanelConfirmation] where req_id=#req_id and process_id=#process_id", con))
{
cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString());
cmd.Parameters.AddWithValue("#req_id", req_id);
exists = (int)cmd.ExecuteScalar();
}
if (exists > 0)
{
query = "select * from CutPanelConfirmation where req_id=#req_id and process_id=#process_id";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString());
cmd.Parameters.AddWithValue("#req_id", req_id);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["process_id"] == "marker")
{
LabelNameMarker.Text = LabelNameMarker.Text + " " + dr[1].ToString();
LabelDateMarker.Text = LabelDateMarker.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "fabric")
{
LabelNameFabric.Text = LabelNameFabric.Text + " " + dr[1].ToString();
LabelDateFabric.Text = LabelDateFabric.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "cutting")
{
LabelNameCutting.Text = LabelNameCutting.Text + " " + dr[1].ToString();
LabelDateCutting.Text = LabelDateCutting.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "SPP")
{
LabelNameSPP.Text = LabelNameSPP.Text + " " + dr[1].ToString();
LabelDateSPP.Text = LabelDateSPP.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "kitting")
{
LabelNameKitting.Text = LabelNameKitting.Text + " " + dr[1].ToString();
LabelDateKitting.Text = LabelDateKitting.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "sew")
{
LabelNameSew.Text = LabelNameSew.Text + " " + dr[1].ToString();
LabelDateSew.Text = LabelDateSew.Text + " " + dr[3].ToString();
}
}
dr.Close();
}
con.Close();
}
}
posting [https://stackoverflow.com/users/7892938/nfh][NFH] answer
i just delete#process id from this query and it works as what i want! :
query = "select * from CutPanelConfirmation where req_id=#req_id and process_id=#process_id"; cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString()); cmd.Parameters.AddWithValue("#req_id", req_id); SqlDataReader dr = cmd.ExecuteReader();
I need to filter an SQL database using C# to display it in a windowsFormsHost.
For that, I created a text box in which you input the required string. Using this input, the code uses the text to search through the database and display on clicking a refresh button.
The refresh button works and is done, I just need to create the list with the selected rows according to my filter.
Here is the code, which states that no value is returned:
private string GetPassengerList(string sPasssenger)
{
string sPasssengerL = textBoxPassengerName.Text;
if (sPasssenger.Trim().Length > 0)
{
string sToTime = dtpToDate.Value.Year.ToString("D4") + #"/" + dtpToDate.Value.Month.ToString("D2") + #"/" + dtpToDate.Value.Day.ToString("D2");
sToTime += #" " + dtpToTime.Value.Hour.ToString("D2") + #":" + dtpToTime.Value.Minute.ToString("D2") + #":" + dtpToTime.Value.Second.ToString("D2");
string sFromTime = dtpFromDate.Value.Year.ToString("D4") + #"/" + dtpFromDate.Value.Month.ToString("D2") + #"/" + dtpFromDate.Value.Day.ToString("D2");
sFromTime += #" " + dtpFromTime.Value.Hour.ToString("D2") + #":" + dtpFromTime.Value.Minute.ToString("D2") + #":" + dtpFromTime.Value.Second.ToString("D2");
string sSqlSelect = #"SELECT Passenger FROM ";
string sSqlWhere = #" WHERE (Created BETWEEN '" + sFromTime + #"' AND '" + sToTime + #"')";// and (IATA='" + sIata + #"')";
string sSqlLike = #" LIKE '%" + sPasssengerL + "'%";
SqlDataReader sqlReader = null;
try {
SqlCommand sqlCommand = new SqlCommand(sSqlSelect + #"dbo.BagData" + sSqlWhere + sSqlLike, this.dbConnection);
sqlReader = sqlCommand.ExecuteReader();
if(!sqlReader.Read()) {
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataHistory" + sSqlWhere + sSqlLike;
sqlReader = sqlCommand.ExecuteReader();
if(!sqlReader.Read()) {
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataArchive" + sSqlWhere + sSqlLike;
sqlReader = sqlCommand.ExecuteReader();
if(!sqlReader.Read()) {
sqlReader.Close();
}
}
}
if(!sqlReader.IsClosed) {
sPasssengerL = this.GetSqlDataString(#"Passenger", sqlReader);
sqlReader.Close();
}
}
catch(SqlException x) {
MessageBox.Show(#"GetPassengerName(): SQL Exception: " + x.Message, this.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
catch(Exception ex) {
MessageBox.Show(#"GetPassengerName(): General Exception: " + ex.Message, this.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
finally {
if(sqlReader != null) {
if(!sqlReader.IsClosed) {
sqlReader.Close();
}
}
}
return sPasssengerL;
}
}
You have a few errors in the code you posted.
Using concatenated strings instead of parameters in your sql query.
Re-declaring a variable with the same name as the functions parameter. You are declaring another passenger variable sPasssengerL needlessly in the function now.
Not returning a string value from the function. Your edited code shows the function returning the seemingly unneeded extra passenger variable sPasssengerL now.
Your LIKE statement did not include which column it is checking
against.
I cleaned up the code a little, leaving the sSqlWhere in case that was oddly delcared outside your example. This also shows how to add the first column of data to a listview as you've requested.
EDIT: Per your comment on the original question I've updated the code
to show your sSqlWhere variable.
private void GetPassengerList()
{
string sPassenger = textBoxPassengerName.Text;
if (sPassenger.Trim().Length > 0)
{
string sToTime = dtpToDate.Value.Year.ToString("D4") + #"/" + dtpToDate.Value.Month.ToString("D2") + #"/" + dtpToDate.Value.Day.ToString("D2");
sToTime += #" " + dtpToTime.Value.Hour.ToString("D2") + #":" + dtpToTime.Value.Minute.ToString("D2") + #":" + dtpToTime.Value.Second.ToString("D2");
string sFromTime = dtpFromDate.Value.Year.ToString("D4") + #"/" + dtpFromDate.Value.Month.ToString("D2") + #"/" + dtpFromDate.Value.Day.ToString("D2");
sFromTime += #" " + dtpFromTime.Value.Hour.ToString("D2") + #":" + dtpFromTime.Value.Minute.ToString("D2") + #":" + dtpFromTime.Value.Second.ToString("D2");
string sSqlSelect = #"SELECT Passenger FROM ";
string sSqlWhere = #" WHERE (Created BETWEEN #startDate AND #endDate)";
// I assume this is looking for passenger. Change appropriately.
string sSqlLike = #"AND Passenger LIKE #name";
string searchTerm = "%" + sPassenger + "%";
SqlDataReader sqlReader = null;
try
{
SqlCommand sqlCommand = new SqlCommand(sSqlSelect + #"dbo.BagData" + sSqlWhere, parentWindow.dbConnection);
sqlReader = sqlCommand.ExecuteReader();
if (!sqlReader.Read())
{
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataHistory" + sSqlWhere + sSqlLike;
sqlCommand.Parameters.Add(new SqlParameter("#name", searchTerm));
sqlCommand.Parameters.Add(new SqlParameter("#startDate", sToTime));
sqlCommand.Parameters.Add(new SqlParameter("#endDate", sFromTime));
sqlReader = sqlCommand.ExecuteReader();
if (!sqlReader.Read())
{
sqlReader.Close();
sqlCommand.CommandText = sSqlSelect + #"dbo.BagDataArchive" + sSqlWhere + sSqlLike;
sqlReader = sqlCommand.ExecuteReader();
// This will loop through your returned data and add
// an item to a list view (listView1) for each row.
while (sqlReader.Read())
{
ListViewItem lvItem = new ListViewItem();
lvItem.SubItems[0].Text = sqlReader[0].ToString();
lvItem.SubItems.Add(sqlReader[0].ToString());
listView1.Items.Add(lvItem);
}
sqlReader.Close();
}
}
if (!sqlReader.IsClosed)
{
sPassenger = parentWindow.GetSqlDataString(#"Passenger", sqlReader);
sqlReader.Close();
}
}
catch (SqlException x)
{
MessageBox.Show(#"GetPassengerName(): SQL Exception: " + x.Message, parentWindow.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
MessageBox.Show(#"GetPassengerName(): General Exception: " + ex.Message, parentWindow.GetHashString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
if (sqlReader != null)
{
if (!sqlReader.IsClosed)
{
sqlReader.Close();
}
}
}
}
}
NOTE: There are other places this code can be cleaned up and simplified but that is beyond the scope of this question.
Check your variables, you've declared sSqlSelect and sSqlLike but not sSqlWhere which you are using in your queries.
a) your function will not compile:
- Missing ";" in several lines,
- local variable declaration "sPessanger" in line 2 conflicts with parameter name ...
b) you never return a value. At least you need a single "return sPassenger;" somewhere in the code to return the selected value.
c) bad style using sql injection. As already stated in the comments, use parameters in your SQL.
d) as far as i can see, you are selecting only a single value from your resultset, or is the GetSqlDataString function supposed to do the job?
I need help for my If Statement, at first it registers into the DB but only the value of 8, even if multiple values are tick. I know my if statements are wrong, but i have no idea what else to do. So should I remove the use another way if it's possible or I just messed a code up? I'm really bad at If's statement.
String points = null;
String ServiceCarWash = "Not Booked";
String ServiceCarPolish = "Not Booked";
String ServiceCarWax = "Not Booked";
int CustomerID = 0;
private void btnBook_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
if (CbCarwash.Checked)
{
ServiceCarWash = "Booked";
}
if (CbCarPolish.Checked)
{
ServiceCarPolish = "Booked";
}
if (CbCarWax.Checked)
{
ServiceCarWax = "Booked";
}
{
if (txtMember.Text.Equals("VIP"))
{
if (ServiceCarPolish == "Booked")
{
points = "20";
}
if (ServiceCarWash == "Booked")
{
points = "2";
}
if (ServiceCarWax == "Booked")
{
points = "8";
}
}
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points = "0";
}
if (ServiceCarWash == "Booked")
{
points = "0";
}
if (ServiceCarWax == "Booked")
{
points = "0";
}
}
string query1 = "UPDATE *Customer set Points='" + points + "'";
OleDbCommand command1 = new OleDbCommand(query1);
command1.Connection = connection;
command1.ExecuteNonQuery();
MessageBox.Show("Your time has been booked.");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
How to accumulate points in code as per comments on previous question. See comments in the below and look out for the += signs.
//String points = null;
int points = 0;
String ServiceCarWash = "Not Booked";
String ServiceCarPolish = "Not Booked";
String ServiceCarWax = "Not Booked";
int CustomerID = 0;
private void btnBook_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
if (CbCarwash.Checked)
{
ServiceCarWash = "Booked";
}
if (CbCarPolish.Checked)
{
ServiceCarPolish = "Booked";
}
if (CbCarWax.Checked)
{
ServiceCarWax = "Booked";
}
{
if (txtMember.Text.Equals("VIP"))
{
if (ServiceCarPolish == "Booked")
{
points += 20;
}
if (ServiceCarWash == "Booked")
{
points += 2;
}
if (ServiceCarWax == "Booked")
{
points += 8;
}
}
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points += 0;
}
if (ServiceCarWash == "Booked")
{
points += 0;
}
if (ServiceCarWax == "Booked")
{
points += 0;
}
}
//string query1 = "UPDATE *Customer set Points='" + points + "'";
string query1 = "UPDATE *Customer set Points='" + points.ToString() + "'";
OleDbCommand command1 = new OleDbCommand(query1);
command1.Connection = connection;
command1.ExecuteNonQuery();
MessageBox.Show("Your time has been booked.");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Set your fields before inserting in to the database.
Move this code to the end of the method (or to just before the Customer update):
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
Also, is *Customer the right table name, should it not just be Customer?
Check the value of your checkboxes to see if they are coming through correctly, then step through your IF's to make sure they calculate correctly. Refactoring in to smaller methods may help you break down the problem so that it is less complex and easier to work with.
Also check your brackets - you have some crazy stuff going on. See the second to last bracket below and you also have something weird going on a bit higher up with a bracket the wrong way around.
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points = "0";
}
if (ServiceCarWash == "Booked")
{
points = "0";
}
if (ServiceCarWax == "Booked")
{
points = "0";
}
**{**
}
Also make sure txtMember.Text always has a value so that points are set. Depending on your input, you can make your code a bit more robust by comparing tolower() in strings, e.g.: txtMember.Text.ToLower().Equals("walk-in").
And step through with the debugger! :)