Reputation: 150
I have got this code down below which should multiply two variables and add to it amount from textbox kpriplac
. but when the multiplied value is 10 and kpriplac value is for example also 10 the output is 1010. But I need that output to be 20. I have also checked this
Where do I make a mistake? Thanks for your time reading this.
if (double.TryParse(comboBoxText, out comboxValue) && int.TryParse(textBox16.Text.Trim(), out textboxValue))
{
textBox19.Text = ((comboxValue * textboxValue) + (kpriplac.Text)).ToString();
}
Upvotes: 1
Views: 1489
Reputation: 28588
+
operator with strings operate as concatenate operator. You need to parse string to int or float.
for example:
textBox19.Text = ((comboxValue * textboxValue) + Convert.ToInt32(kpriplac.Text)).ToString();
Pleas make sure kpriplac.Text
is:
If it then handle accordingly.
Upvotes: 2
Reputation: 32729
You face this because
(comboxValue * textboxValue)
is an integer,whereas
kpriplac.Text
is a string
In C# string + int = string. So lets say multiplication returns you 10. And you have got 10 in your text box as well
so what will happen is
10 + "10" = 1010
Change your code to
if (double.TryParse(comboBoxText, out comboxValue) && int.TryParse(textBox16.Text.Trim(), out textboxValue))
{
int tempValue = 0;
if(int.TryParse(kpriplac.Text,out tempValue))
textBox19.Text = ((comboxValue * textboxValue) + tempValue).ToString();
}
Upvotes: 1
Reputation: 671
You need to call int.Parse on every string, and then multiply or add the parsed values together, finally converting them back to string.
Use int.Parse only if you're sure that the given string is indeed an integer. If it isn't, exceptions are thrown. If you're unsure and want to handle them manually, use int.TryParse instead.
Upvotes: 1
Reputation: 116538
As it stands, your code is adding a number to a string which is implicitly calling ToString()
on the (comboxValue * textboxValue)
expression and performing string concatenation.
You need to parse the value in kpriplac.Text
into a numeric type as well, in much the same manner you are doing for comboBoxText
and textBox16.Text
.
Upvotes: 2
Reputation: 1526
Try this
Convert.ToInt32(((comboxValue * textboxValue) + (kpriplac.Text))).ToString();
Upvotes: 0