I'm not getting any errors and I'm a bit lost on where to look to solve the problem (my first project - Probably way over my head heh). The Amount and Settlement amount both save to the table but the combobox options aren't saving. The Access fields are set to Short Text (if that helps).
I'm not looking for a hand me out but rather if someone could point me in the right direction to get this solved.
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
connection.Open();
//converting data entered to be imported into Access tblePayments
string EmployeeConverted;
double AmountConverted;
string ClientConverted;
string PaymentMethodConverted;
string PaymentTypeConverted;
string MonthConverted;
int SettlementConverted;
EmployeeConverted = Convert.ToString(cboxEmployee.SelectedValue);
AmountConverted = Convert.ToDouble(txtAmount.Text);
ClientConverted = Convert.ToString(cboxClient.SelectedValue);
PaymentMethodConverted = Convert.ToString(cboxPaymentMethod.SelectedValue);
PaymentTypeConverted = Convert.ToString(cboxPaymentType.SelectedValue);
MonthConverted = Convert.ToString(cboxMonth.SelectedValue);
SettlementConverted = Convert.ToInt32(txtSettlement.Text);
//inserting converted data into Access
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into tblePayments (Employee, AmountofPayment, Client, PaymentMethod, PaymentType, MonthofPayment, Settlement) values('" + EmployeeConverted + "', " + AmountConverted + ", '" + ClientConverted + "', '" + PaymentMethodConverted + "', '" + PaymentTypeConverted + "', '" + MonthConverted + "', " + SettlementConverted + ")";
command.ExecuteNonQuery();
MessageBox.Show("Payment Saved");
connection.Close();
}
catch (Exception error)
{
MessageBox.Show("Error: " + error);
}
Related
When debugging, an error happens on this line of code:
int StartKmReading = Convert.ToInt32(txtDTStartKmReading);
This is the errpr
System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.IConvertible'
Data types and names of the database are correct as well.
Please help me with this. Thanks
private void btnAddDT_Click(object sender, EventArgs e)
{
try
{
String InvoiceNo = txtDTInvoice.Text;
String VehicleNo = txtDTVehicleNo.Text;
String PackageType = txtDTPackageType.Text;
DateTime StartTime = dtpStartTimeDT.Value;
DateTime EndTime = dtpEndtimeDT.Value;
int StartKmReading = Convert.ToInt32(txtDTStartKmReading);
int EndKmReading = Convert.ToInt32(txtDTEndKmReading.Text);
double BaseHire = Convert.ToDouble(txtBaseHireChargeDT.Text);
double WaitingFee = Convert.ToDouble(txtWaitingFeeDT.Text);
double ExtraKmCharge = Convert.ToDouble(txtExtraKmChargeDT.Text);
double TotalAmount = Convert.ToDouble(txtDTTotalAmountCal.Text);
conn.Open();
String addQ = "insert into DayTourHires Values ('" + InvoiceNo + "', '" + VehicleNo + "', '" + PackageType + "', '" + StartTime+ "', '" + EndTime + "', '" + StartKmReading + "', '" + EndKmReading + "', '" + BaseHire + "', '" + WaitingFee + "', '" + ExtraKmCharge + "', '" + TotalAmount + "')";
SqlCommand comm = new SqlCommand(addQ, conn);
comm.ExecuteNonQuery();
MessageBox.Show("Record inserted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
The data should be successfully stored in the database without errors.
The issue is in this line code
int StartKmReading = Convert.ToInt32(txtDTStartKmReading);
It should be:
int StartKmReading = Convert.ToInt32(txtDTStartKmReading.Text);
But be careful. If the user enter a not valid value in the textboxes your code will throw an exception.
You should use int.TryParse method to make your code stronger
Trying to update records in my datatable using textboxes on a button click. The error message says is cannot insert a duplicate value, and shows the value that I have entered into txtID. This is the code for the update button:
private void btnUpdate_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand command = new SqlCommand();
String query = "UPDATE Bug SET Tester_ID=" + txtID.Text + "',Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "')";
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
adapter.SelectCommand.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Updated Successfully");
}
You do not have where clause in that query, so it is updating all records in the table, which is making some records duplicate. Hence the error.
The could be due to your defined table structure.
P.S. You should look for SQL injection attack and should parameterize your query to avoid it.
Edit based on your comment
String query = "UPDATE Bug Set Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "' WHERE Tester_ID='" + txtID.Text + "'";
If Tester_Id is numeric, you don't need those quotes.
Where clause comes after Set.
Here is the Parameterized version:
String query = "UPDATE Bug Set Tester_Name=#Tester_Name,Application_Name= #AppName,Class_Name= #Class_Name,Line_No= #Line_No,Error_Description= #Error_Description,Source_Code= #Source_Code,Status= #Status WHERE Tester_ID=#Tester_ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#Tester_Name", "XYZ");
// other params
command.Parameters.AddWithValue("#Tester_ID", 10);
Please help me out in this error.
I am using access database in C# and developing WPF application. Here, I am writing updating query and i got the below error :-
"Data type mismatch in criteria expression".
Here, Retail and Cut_Off both are checkbox. I added it later.When I added checkbox later it gives me this error.
I stored checkbox value like below :-
cmentity.Retail = chkRetailIndividualBidder.IsChecked.Value.ToString();
cmentity.Cut_Off = chkCutOff.IsChecked.Value.ToString();
Below code wrote in Clientmasterrepository.cs file
public int UpdateForAllClientInfo(ClientMaster cmentity)
{
string strQuery = "UPDATE ClientMaster SET " +
"Applied_Quantity = '" + cmentity.Applied_Quantity + "', " +
"Amount = '" + cmentity.Amount + "', " +
"Cheque_in_Favour = '" + cmentity.Cheque_in_Favour + "', " +
"Retail_Individual_Bidder = '" + cmentity.Retail + "', " +
"Cut_Off = '" + cmentity.Cut_Off + "' " +
"WHERE IsDeleted = " + 0;
return oConnectionClass.ExecuteNonQuery(strQuery);
}
below code wrote in connection.cs file:-
public int ExecuteNonQuery(string strQuery)
{
OleDbConnection oleDbConnection = new OleDbConnection(strConnectionString);
OleDbCommand oleDbCommand = new OleDbCommand(strQuery, oleDbConnection);
oleDbCommand.CommandText = strQuery;
oleDbCommand.CommandType = CommandType.Text;
oleDbConnection.Open();
oleDbCommand.ExecuteNonQuery();
oleDbConnection.Close();
return 1;
}
I am having a problem inserting a record, the error says, "Error converting data type varchar to numeric."
This is my set of codes:
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
txtPONo.Text + "', '0', 'Agent', '" +
txtInvoiceNo.Text + "', '" +
lblTotal.Text + "', 'Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
txtOrderNo.Text = nShoppingCart.ToString();
cmdInsert.ExecuteNonQuery();
cn.Close();
}
the highlighted part is the
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
I cannot seem to know where is the problem? thank you for your help.
I think you have taken "CustomerNo" field in database numeric field and you are trying to insert varchar or string value in that field as i am able to see your code in which you are putting "txtCustomerNo.Text" which will contain string value. You should convert your value fisrt in int or whatever you have taken your database field.
Hopefully this will be helpful for you.
Can you run the script without the Convert method. Replace it with:
string nShoppingCart = cmdInsert.ExecuteScalar().ToString();
Then see what nShoppingCart value is, and see if that would ever convert to an integer.
Try adding following part
Convert.ToInt16(lblTotal.Text)
this problem is a bit of a difficult one to explain but here it goes. I have a function which adds a record to a MySQL Database online from a local SQLiteDatabase. A function is first called to retrieve the local data and each line is sent to the upload function which adds the record to the online MySQL Database. When these functions are called from a another function A it works fine but when called from a different function. Function B duplicate records are entered into the database.
During debugging to try and resolve the problem I find that when it is duplicating records it is going to cmd.executeNonQuery() then going to the next couple of line but then for no reason will go back up to cmd.executeNonQuery() therefore duplicating the record. The code is below
private void uploadDatabase(string company, string oldCompany, string companyURL, string loginUsername, string oldUsername, string password, string type, string perform, string direction)
{
Boolean recordFound = false;
recordFound = checkRecordNotExist(company, loginUsername);
MySQLDBWork dbase = new MySQLDBWork();
try
{
dbase.openConnection();
if (perform == "insert" && !recordFound)
{
string query = "INSERT INTO `" + username + "` (pas_company, pas_companyURL, pas_username, pas_password, pas_type) "
+ "VALUES ('" + company + "', '" + companyURL + "', '" + loginUsername + "', '" + password + "', '" + type + "')";
Console.WriteLine("Query: " + query);
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);
cmd.ExecuteNonQuery();
recordFound = true;
query = "";
company = "";
loginUsername = "";
cmd.Dispose();
}
if (perform == "delete")
{
string query = "DELETE FROM `" + username + "` WHERE pas_company='" + company + "' AND pas_username='" + loginUsername + "'";
dbase.performQuery(query);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Adding Online Error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
finally
{
dbase.closeConnection();
//dbase.conn.Dispose();
company = null;
loginUsername = null;
}
}
The problem is within the if statement perform == "insert" && !recordFound.
I'm not sure if the code above will help to solve the problem but this is the function that is going wrong when called from function b but works fine from function A. Thanks for any help and suggestions you can offer.
then going to the next couple of line
but then for no reason will go back up
to cmd.executeNonQuery()
That sounds like a simple multithreading problem. The function is accessed again from a different thread. So what's happening is that it goes through your check exists in both threads before it is inserted in either, and then it is inserted in both.
So, create a lock, and lock the code... something like this:
private System.Object uploadLock = new System.Object();
private void uploadDatabase(string company, string oldCompany, string companyURL, string loginUsername, string oldUsername, string password, string type, string perform, string direction)
{
lock(uploadLock ) {
Boolean recordFound = false;
recordFound = checkRecordNotExist(company, loginUsername);
MySQLDBWork dbase = new MySQLDBWork();
try
{
dbase.openConnection();
if (perform == "insert" && !recordFound)
{
string query = "INSERT INTO `" + username + "` (pas_company, pas_companyURL, pas_username, pas_password, pas_type) "
+ "VALUES ('" + company + "', '" + companyURL + "', '" + loginUsername + "', '" + password + "', '" + type + "')";
Console.WriteLine("Query: " + query);
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);
cmd.ExecuteNonQuery();
recordFound = true;
query = "";
company = "";
loginUsername = "";
cmd.Dispose();
}
if (perform == "delete")
{
string query = "DELETE FROM `" + username + "` WHERE pas_company='" + company + "' AND pas_username='" + loginUsername + "'";
dbase.performQuery(query);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Adding Online Error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
finally
{
dbase.closeConnection();
//dbase.conn.Dispose();
company = null;
loginUsername = null;
}
}
}
The lock will allow access to the code to only on thread at a time. So no more duplications.
My advice to you:
Always use transactions and you won't be able make duplications. You also may make LoginName column unique and properly handle db error.
DO NOT concatenate string to build query, please. Use command parameters - simplest way escape SQL injection. Currently you have at least 4 vulnerable parameter. Awesome ;)
I would suggest putting a breakpoint on cmd.ExecuteNonQuery(); and inspecting the call stack each time it is hit, paying special attention to the second/duplicate hit. Also pay attention to which thread the breakpoint is being hit on. Doing these things should point you to the problem.