Click here to Skip to main content
15,314,303 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i recently changed my code from to c#
now i get an error regarding text

TxtQty.Text -= 1.ToString();

tnx for any help
arik :)

What I have tried:

tried to convert but nothing helped
Updated 14-Oct-21 23:07pm

You can't subtract a string from a string, you have to convert the values into number types before you can do that.
TxtQty.Text = Convert.ToString(int.Parse(TxtQty.Text) - 1);

Which converts the quantity value into an int, subtracts one, then assigns it back. I'd recommend adding more validation however, perhaps using int.TryParse() to check whether the value of the quantity text is a valid number.
Arik m 15-Oct-21 9:09am
thank you
There is no operation which allows your to use a "-=" operator on a string: concatenation is simple with "+=", as it's obvious you want the second string appended to the end of the existing data. But ... what should "-=" so? Remove all instances of the new string? Trim the end? Something else?
As a result, it's not a defined operator for strings.

If you want to take a text box containing a number and reduce it by one, you have to use int.TryParse to convert the text to a number (reporting problems if any), subtract one, then converter the result back to a string:
int qty;
if (!int.TryParse(TxtQty.Text, out qty))
   ... report problems ...
TxtQty.Text = (qty - 1).Tostring();
VB makes guesses about what you wanted to do and converts types willy-nilly (and causes a lot of problems in the process): C# doesn't baby you and assume you are an idiot - it wants you to be precise about what you want, and tell it exactly what to do. That way, problems like this are caught at compile time instead of run time, which is much better for reliability purposes.
Arik m 15-Oct-21 9:12am
thank you
OriginalGriff 15-Oct-21 9:57am
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900