views:

747

answers:

4

Please, help me to identify problem in my C# code(WPF, event-handler):

        private void Discount5Btn_Click(object sender, RoutedEventArgs e)
    {
        decimal catPr;
        decimal salePr;
        string catPrStr;
        catPrStr = PriceCatTBox.Text;
        catPr = decimal.Parse(catPrStr);
        salePr = decimal.Multiply(catPr, 0.95m);
        SalePriceTBox.Text = (salePr).ToString("0000.00");
    }

I can not make it work - debugger shows error on catPr = decimal.Parse(catPrStr); . Very similar code in another place works. And am I right in such an approach to string-decimal conversion for arithmetic operation?

Edit (added)

Sorry for not specifying catPrStr value, it is from textbox in the following code (in another event-handler):

dlg.PriceCatTBox.Text = "2300.00";
....

and then as above:

catPrStr = PriceCatTBox.Text;
+1  A: 

We can't help you because we don't know the value of catPrStr, you are converting from String to Decimal and most likely the value of the string being converted is incorrect.

Stan R.
thanks, I have added content about "catPrStr" variable in my initial question
rem
+1 Yes, it was there
rem
+1  A: 

decimal.TryParse(catPrStr, out catPr); and handle the bool return from it to ensure that you have a reasonable value to process.

jball
+3  A: 

And am I right in such an approach to string-decimal conversion for arithmetic operation?

I would set up two way binding with a model to store your decimal values. This will allow you to access them directly instead of parsing strings. This will also solve your error.

Ragepotato
WPF has many hooks for data binding and will make this relatively trivial.
Ragepotato
+1 WPF data binding and the MVVM pattern is designed to remove the necessity to do these kinds of conversions manually
AdamRalph
+1 Thanks, I will for sure learn and use it
rem
+2  A: 

Are you sure your culture (locale) settings aren't interfering? If catPrStr is always in the invariant culture shown in your edited question, you could use decimal.TryParse(catPrStr, CultureInfo.InvariantCulture); to force the usage of that culture. If the culture isn't specified, parsing is done in the current system culture, which might, for example, use a comma as the decimal separator.

TomiJ
I didn't manage to implement the code with suggested "TryParse" method, but the problem was in commas indeed. After I change "dlg.PriceCatTBox.Text = "2300.00";" to .."2300,00".. everything worked OK. Thanks!
rem
Note that if you hard-code the value like that, it will fail in some other culture. You might want to use for example `dlg.PriceCatTBox.Text = 2300.00.ToString("0.00")` instead.
TomiJ