Question
In C#, I need to Sum all values in a list box that are in the format $32.21 etc. etc. etc. These values are entered
In C#, I need to Sum all values in a list box that are in the format "$32.21" etc. etc. etc.
These values are entered into the list box by selecting one of five radio buttons and entering a quantity to add the sale price for that item to the list box.
The user should then be able to hit a total button to sum all the values in the list box.
There could be a single value or there may be up to 10 values or more in the list box that all need to be summed,
I have inserted a sample of the code I am using below.
The line giving me the error is
decimal total = (decimal.Parse(TotalPrice, System.Globalization.NumberStyles.Currency));
it returns a System.FormatException: 'Input string was not in a correct format.' error
The first part of the code for adding the values to the list box is working fine. How can I sum the values in the list box using the current method? I hope someone can help with this, thank you very much in advance.
private void BtnCalculate_Click(object sender, EventArgs e) { // Declare quantity variable convertted from Quantity text box decimal quantity = Convert.ToDecimal(TxtQuanity.Text);
//Determine Product price using a Switch statement
RadioButton radioBtn = this.Controls.OfType
if (radioBtn != null) { switch (radioBtn.Name) { //Calculate total sale by multiplying product price by quantity //append result to list box case "RdbProduct1": decimal cost = 3.99m; decimal subtotal = quantity * cost; LstSuccess.Items.Add(subtotal.ToString("c")); break; case "RdbProduct2": decimal cost1 = 1.40m; decimal subtotal1 = quantity * cost1; LstSuccess.Items.Add(subtotal1.ToString("c")); break; case "RdbProduct3": decimal cost2 = 2.10m; decimal subtotal2 = quantity * cost2; LstSuccess.Items.Add(subtotal2.ToString("c")); break; case "RdbProduct4": decimal cost3 = 5.01m; decimal subtotal3 = quantity * cost3; LstSuccess.Items.Add(subtotal3.ToString("c")); break; case "RdbProduct5": decimal cost4 = 1.98m; decimal subtotal4 = quantity * cost4; LstSuccess.Items.Add(subtotal4.ToString("c")); break; } } }
private void BtnTotal_Click(object sender, EventArgs e) {
string TotalPrice = LstSuccess.Items.ToString(); decimal total = (decimal.Parse(TotalPrice, System.Globalization.NumberStyles.Currency)); LblMessage.Text = total.ToString();
} } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started