Reputation: 9
Good day everyone! Hope this work. I have to 2 textboxes and I convert it to integer the num1 and num2. I want to display it into textSubtotal. For example 10 * 10 = 100. I want to multiply another 2 numbers the value is 20 * 20 = 400. Add it to 100 so the answer will be 100 + 400 = 500. But the problem is I received an error in this line textSubtotal.Text = Convert.ToString(float.Parse(textSubtotal.Text) + sum)
Input string was not in a correct format. Can somebody help me regarding to my problem?
private void buttonOrder_Click(object sender, EventArgs e)
{
float num1, num2, product = 0, sum = 0;
num1 = float.Parse(textPrice.Text);
num2 = float.Parse(textQuantity.Text);
product = num1 * num2; sum = sum + product;
textSubtotal.Text = Convert.ToString(float.Parse(textSubtotal.Text) + sum);
}
Upvotes: 0
Views: 619
Reputation: 3754
You don't need to struggle with Textbox string conversions to do that. Use a private field:
private float subTotal = 0; // this would be a field in your class
private void buttonOrder_Click(object sender, EventArgs e)
{
float num1 = float.Parse(textPrice.Text);
float num2 = float.Parse(textQuantity.Text);
subTotal += num1 * num2;
textSubtotal.Text = subTotal;
}
You should check that the two fields contain actual numeric values (see float.TryParse()
). Also, consider using decimal
(not float
) for this kind of calculations.
Upvotes: 1