Question

I am working a small sale invoice application on WF. I have a customer table and a product table. Then, I populate customer name and product name via comboboxes on Sale-form. Once user selects an item from ProductName combobox, other textboxes like Price and ProductID are auto-populated with data from Product Table from database. I have also a textbox named txtQuantity that can be entered for Quantity for product order. Once a number is entered for Quantity, subtotal, GST(which is Tax in Singapore), and total are auto-calculated and those values appear on textboxes of Subtotal, GST and Total. When a user delete quantity to update/change, it shows error as "Format Exception was unhanded, input string was not in a correct format". I like to prevent this error to stop working my application when user delete quantity or want to change to a new value. How do I go about it because I am complete lost here. Below is my code.

private void txtQuantity_TextChanged(object sender, EventArgs e)
{
   int iQuantity = Convert.ToInt32(txtQuantity.Text);

   decimal dPrice = Convert.ToDecimal(txtPrice.Text);

   decimal dSubtotal = dPrice * iQuantity;
   decimal dGST = dSubtotal * 7/100;
   decimal dTotal = dSubtotal + dGST;

    txtSubTotal.Text = Convert.ToString(dSubtotal);
    txtGST.Text = Convert.ToString(dGST);
    txtTotal.Text = Convert.ToString(dTotal);

}

I also wanted to set parameters for quantity textbox as only for entering numbers. I will do that later. This is going to be another thing to explore. Any advice for this is also welcomed and appreciated.

Was it helpful?

Solution

I would run all of your string inputs through the following (or something similar) before trying to assign them to an integer variable, especially when dealing with direct user input.

string myVar1;

//Something that assigns a value to myVar1

if(String.IsNullOrEmpty(myVar1))
{
 myVar1 = "0";
}
else
{
  int number;
  bool result = Int32.TryParse(myVar1, out number);
  if (result)
  {
     //you have a valid input and valid parse, do whatever you need with number     variable     
  }
  else
  {
    //bad input, reset to blank and show error message
  }

}

Note the above code is an example and while fairly close to what you probably want, you will need to modify it before just copy/pasting it into your application

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top