Hello Team,
When I try saving into the database it work perfectly but return this respond saying that input string was not in the correct format.
private void btn_Save_Click(object sender, EventArgs e)
{
if (txt_Productname.Text == "" || txt_CostPrice.Text == "" || txt_SalesPrice.Text == "")
{
MessageBox.Show("Missing Information !!!");
}
else
{
try
{
if (MessageBox.Show("Please confirm if you want to save this product?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
decimal Profit = Convert.ToDecimal(txt_SalesPrice.Text) - Convert.ToDecimal(txt_CostPrice.Text);
cn.Open();
cm = new SqlCommand("INSERT INTO tblProduct(PCode,ProductDate,ProductName, Category, CostPrice,Profit,SalesPrice,Tax,TotalPrice,Barcode)VALUES(@pCode,@productDate,@productName, @category, @costPrice,@profit,@salesPrice,@tax,@totalPrice,@barcode)", cn);
cm.Parameters.AddWithValue("@pCode", txt_ProductCode.Text);
cm.Parameters.AddWithValue("@productDate", DbType.Date).Value = dtProductDate.Value;
cm.Parameters.AddWithValue("@productName", txt_Productname.Text);
cm.Parameters.AddWithValue("@category", cbo_Category.Text);
cm.Parameters.AddWithValue("@costPrice", txt_CostPrice.Text);
cm.Parameters.AddWithValue("@profit", Profit);
cm.Parameters.AddWithValue("@salesPrice", txt_SalesPrice.Text);
cm.Parameters.AddWithValue("@tax", cbo_Tax.Text);
cm.Parameters.AddWithValue("@totalPrice", txt_TotalPrice.Text);
// cm.Parameters.AddWithValue("@stockIn", txt_Stock.Text);
cm.Parameters.AddWithValue("@barcode", txt_Barcode.Text);
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Product has been successfully saved!", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
Clear();
fm.LoadCategory();
}
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message);
}
}
}
and
private void cbo_Tax_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
decimal salesPrice = decimal.Parse(txt_SalesPrice.Text);
decimal tax = decimal.Parse(cbo_Tax.Text);
decimal total = (salesPrice * tax / 100) + salesPrice;
txt_TotalPrice.Text = total.ToString("#,##0.00");
}
catch (Exception ex)
{
throw ex;
}
}

Jithu ThomasRank #437 · 5.7K reputationPosted May 30, 2024, 2:03 PM EDT
Mr. Emmanual
As per prasad we connected and solve your problem please accept my answer if you found the same was helpfull
Jignesh KumarRank #91 · 22.9K reputationPosted May 25, 2024, 2:17 AM EDT
Hi,
Then you need to check in this method fm.LoadCategory();
Could you please share the code for this method ?
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 25, 2024, 6:45 AM EDT
Hello Kumar
public void LoadCategory()
{
cbo_Category.Items.Clear();
try
{
int i = 0;
// dataGridView1.Rows.Clear();
cn.Open();
cm = new SqlCommand("select * from tblCategory", cn);
dr = cm.ExecuteReader();
while (dr.Read())
{
i++;
cbo_Category.Items.Add(dr["CategoryName"].ToString());
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message);
}
}
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 25, 2024, 6:47 AM EDT
Hello Thomas,
I tried that format before but the error still came
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 25, 2024, 11:47 AM EDT
Hello Thomas.
Error Message is this and the table struction
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 25, 2024, 1:55 PM EDT
Hello Mr. Thomas,
Please as I change the way you said it, this is the error that popup
Prasad RaveendranRank #320 · 7.8K reputationPosted May 25, 2024, 11:47 PM EDT
Could you please try this way.
Save Button Click Event
private void btn_Save_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txt_Productname.Text) || string.IsNullOrWhiteSpace(txt_CostPrice.Text) || string.IsNullOrWhiteSpace(txt_SalesPrice.Text)) { MessageBox.Show("Missing Information !!!"); return; } if (!decimal.TryParse(txt_CostPrice.Text, out decimal costPrice) || !decimal.TryParse(txt_SalesPrice.Text, out decimal salesPrice)) { MessageBox.Show("Cost Price and Sales Price must be numeric values."); return; } decimal profit = salesPrice - costPrice; try { if (MessageBox.Show("Please confirm if you want to save this product?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { cn.Open(); cm = new SqlCommand("INSERT INTO tblProduct(PCode,ProductDate,ProductName, Category, CostPrice,Profit,SalesPrice,Tax,TotalPrice,Barcode) " + "VALUES(@pCode,@productDate,@productName, @category, @costPrice,@profit,@salesPrice,@tax,@totalPrice,@barcode)", cn); cm.Parameters.AddWithValue("@pCode", txt_ProductCode.Text); cm.Parameters.AddWithValue("@productDate", dtProductDate.Value); cm.Parameters.AddWithValue("@productName", txt_Productname.Text); cm.Parameters.AddWithValue("@category", cbo_Category.Text); cm.Parameters.AddWithValue("@costPrice", costPrice); cm.Parameters.AddWithValue("@profit", profit); cm.Parameters.AddWithValue("@salesPrice", salesPrice); if (!decimal.TryParse(cbo_Tax.Text, out decimal tax)) { MessageBox.Show("Tax must be a numeric value."); cn.Close(); return; } cm.Parameters.AddWithValue("@tax", tax); if (!decimal.TryParse(txt_TotalPrice.Text, out decimal totalPrice)) { MessageBox.Show("Total Price must be a numeric value."); cn.Close(); return; } cm.Parameters.AddWithValue("@totalPrice", totalPrice); cm.Parameters.AddWithValue("@barcode", txt_Barcode.Text); cm.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Product has been successfully saved!", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information); Clear(); fm.LoadCategory(); } } catch (Exception ex) { cn.Close(); MessageBox.Show(ex.Message); } }Tax ComboBox SelectedIndexChanged Event
private void cbo_Tax_SelectedIndexChanged(object sender, EventArgs e) { try { if (decimal.TryParse(txt_SalesPrice.Text, out decimal salesPrice) && decimal.TryParse(cbo_Tax.Text, out decimal tax)) { decimal total = (salesPrice * tax / 100) + salesPrice; txt_TotalPrice.Text = total.ToString("#,##0.00"); } else { MessageBox.Show("Sales Price and Tax must be numeric values."); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }LoadCategory method looks fine, but ensure that the category names in your tblCategory table are all valid strings and there's no unexpected data.
Final Notes
Parameter Types in SQL: Use the correct data types when adding parameters to your SQL command, especially for dates and decimals.
User Input Validation: Always validate user input before processing it, ensuring that non-numeric values don't cause exceptions when converting to numeric types.
Error Handling: Handle parsing errors gracefully to provide clear feedback to the user instead of allowing exceptions to occur.
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 26, 2024, 10:02 AM EDT
Hello Prasad
This is the error that is poping up
The combobox
The save button
The save buttons
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 26, 2024, 10:13 AM EDT
Hello Thomas.
Please your format isn't working form me
Prasad RaveendranRank #320 · 7.8K reputationPosted May 27, 2024, 6:37 PM EDT
Hello Emmanuel,
My apologies. My first question should have been which C# version you are using. The syntax I provided was introduced in C# 7.0.
Here is the modified code. Please try and let me know
private void btn_Save_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txt_Productname.Text) || string.IsNullOrWhiteSpace(txt_CostPrice.Text) || string.IsNullOrWhiteSpace(txt_SalesPrice.Text)) { MessageBox.Show("Missing Information !!!"); return; } decimal costPrice; decimal salesPrice; if (!decimal.TryParse(txt_CostPrice.Text, out costPrice) || !decimal.TryParse(txt_SalesPrice.Text, out salesPrice)) { MessageBox.Show("Cost Price and Sales Price must be numeric values."); return; } decimal profit = salesPrice - costPrice; try { if (MessageBox.Show("Please confirm if you want to save this product?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { cn.Open(); cm = new SqlCommand("INSERT INTO tblProduct(PCode,ProductDate,ProductName, Category, CostPrice,Profit,SalesPrice,Tax,TotalPrice,Barcode) " + "VALUES(@pCode,@productDate,@productName, @category, @costPrice,@profit,@salesPrice,@tax,@totalPrice,@barcode)", cn); cm.Parameters.AddWithValue("@pCode", txt_ProductCode.Text); cm.Parameters.AddWithValue("@productDate", dtProductDate.Value); cm.Parameters.AddWithValue("@productName", txt_Productname.Text); cm.Parameters.AddWithValue("@category", cbo_Category.Text); cm.Parameters.AddWithValue("@costPrice", costPrice); cm.Parameters.AddWithValue("@profit", profit); cm.Parameters.AddWithValue("@salesPrice", salesPrice); decimal tax; if (!decimal.TryParse(cbo_Tax.Text, out tax)) { MessageBox.Show("Tax must be a numeric value."); cn.Close(); return; } cm.Parameters.AddWithValue("@tax", tax); decimal totalPrice; if (!decimal.TryParse(txt_TotalPrice.Text, out totalPrice)) { MessageBox.Show("Total Price must be a numeric value."); cn.Close(); return; } cm.Parameters.AddWithValue("@totalPrice", totalPrice); cm.Parameters.AddWithValue("@barcode", txt_Barcode.Text); cm.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Product has been successfully saved!", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information); Clear(); fm.LoadCategory(); } } catch (Exception ex) { cn.Close(); MessageBox.Show(ex.Message); } }private void cbo_Tax_SelectedIndexChanged(object sender, EventArgs e) { try { decimal salesPrice; decimal tax; if (decimal.TryParse(txt_SalesPrice.Text, out salesPrice) && decimal.TryParse(cbo_Tax.Text, out tax)) { decimal total = (salesPrice * tax / 100) + salesPrice; txt_TotalPrice.Text = total.ToString("#,##0.00"); } else { MessageBox.Show("Sales Price and Tax must be numeric values."); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 28, 2024, 6:20 AM EDT
Hello Prasad Raveendran
The response that is coming from the combobox after trying your new code is saying that salesPrice and tax must be numeric value but I enter numeric value and it did save in the database as numeric value so how come this after save error response is coming
Prasad RaveendranRank #320 · 7.8K reputationPosted May 28, 2024, 8:12 PM EDT
It's possible that the
Clear()orfm.LoadCategory()methods might be causing issues, especially if they are clearing or reloading values in a way that interferes with subsequent event handlers. To investigate, let's look at what these methods do and make sure they don't inadvertently clear necessary data or trigger events that cause parsing to fail.Please set breakpoints in these two methods and then click the Save button. Debug these methods to identify the cause of the error message.
Please share the code for Clear() as well here.
Jithu ThomasRank #437 · 5.7K reputationPosted May 25, 2024, 2:22 AM EDT
Dear Emmmanuel FIADUFE,
i strongly guess the below line of code is creating the problem.
cm.Parameters.AddWithValue("@productDate", DbType.Date).Value = dtProductDate.Value;
please change the same as follows: -
cm.Parameters.AddWithValue("@productDate", dtProductDate.Value.ToString("yyyy-MM-dd"));
Jithu ThomasRank #437 · 5.7K reputationPosted May 25, 2024, 10:43 AM EDT
Mr. Emmmanuel FIADUFE
Can u show me a screenshot of the error. also check the stucture of the database table.
Regards,
Jithu ThomasRank #437 · 5.7K reputationPosted May 26, 2024, 2:59 AM EDT
Mr. Emmaanuel
The problem as you are not converting the text value into decimal. try this -
Convert.ToDecimal(textBoxPrice.Text);
This will solve the issue.
Jithu ThomasRank #437 · 5.7K reputationPosted May 26, 2024, 4:52 AM EDT
I tried this way and it works for me: -
CREATE TABLE Products ( ProductID INT PRIMARY KEY, ProductName VARCHAR(100), Price DECIMAL(18, 2) );using System; using System.Data.SqlClient; using System.Windows.Forms; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void buttonInsert_Click(object sender, EventArgs e) { try { decimal price = Convert.ToDecimal(textBoxPrice.Text); InsertData(price); } catch (FormatException) { MessageBox.Show("Please enter a valid decimal number for the price."); } } private void InsertData(decimal price) { string connectionString = "YourConnectionStringHere"; string query = "INSERT INTO Products (ProductName, Price) VALUES (@ProductName, @Price)"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@ProductName", "Sample Product"); command.Parameters.AddWithValue("@Price", price); try { connection.Open(); int result = command.ExecuteNonQuery(); if (result < 0) MessageBox.Show("Error inserting data into Database!"); else MessageBox.Show("Data inserted successfully!"); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } } }Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 29, 2024, 6:18 AM EDT
Thank you Prasad, it is the clear function that is causing the problem
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted May 30, 2024, 2:28 PM EDT
Yes Thomas that's true, thank you so much and I really appreciate your help