WireIsCool
WireIsCool

Reputation: 11

How do you add numbers to an int?

I'm trying to make a basic calculator in c#.

The only problem is, I don't know how I could add numbers to an int; for instance, if I wanted button1 to do something like this in a textbox, it'd be

textBox1.text += "1"

but this is for the operations, and the textbox displays the operator, so I couldn't convert it to an int. I'd really appreciate some help.

Upvotes: 0

Views: 221

Answers (2)

ChrisV
ChrisV

Reputation: 1309

C# is a strongly typed language. A textbox contains a string, which you must convert to an int before performing arithmetical operations.

Converting a string to an int can be done with int.Parse(), then you must convert back to a string to change the textbox contents:

int temp = int.Parse(textBox1.Text) + 1;
textBox1.Text = temp.ToString();

This will throw an exception if textBox.Text cannot be converted to an int. To deal with this, look up the int.TryParse() function.

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881223

You can do it with something like (where s is a string):

s = (Int32.Parse(s) + 1).ToString();

Just make sure that s is actually a valid number, otherwise you'll have to cobble together something with TryParse and figure out what to do when it's not a number, like leave it alone:

int val;
if (Int32.TryParse(s, out val)) {
    val++;
    s = val.ToString();
}

You can also restrict user input so that they can only enter integers, have a look at MaskedTextBox and set the Mask property. See the documentation here.

Upvotes: 2

Related Questions