Add numbers in c#

2019-01-29 01:53发布

i have a numerical textbox which I need to add it's value to another number I have tried this code

String add = (mytextbox.Text + 2)

but it add the number two as another character like if the value of my text box is 13 the result will become 132

标签: c# numbers add
7条回答
太酷不给撩
2楼-- · 2019-01-29 02:07
string add=(int.Parse(mytextbox.Text) + 2).ToString()

if you want to make sure the conversion doesn't throw any exception

  int textValue = 0;
  int.TryParse(TextBox.text, out textValue);
  String add = (textValue + 2).ToString();
查看更多
Bombasti
3楼-- · 2019-01-29 02:08

You can use the int.Parse method to parse the text content into an integer:

String add = (int.Parse(mytextbox.Text) + 2).ToString();
查看更多
别忘想泡老子
4楼-- · 2019-01-29 02:12

Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.

This might be a good approach if you need to reuse the integer several times:

private int MyTextBoxInt
{
    get
    {
        return Int32.Parse(mytextbox.Text);
    }
}

And then you can use the property like this:

int result = this.MyTextBoxInt + 2;
查看更多
该账号已被封号
5楼-- · 2019-01-29 02:15
String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();

You need to convert the text to an integer to do the calculation.

查看更多
男人必须洒脱
6楼-- · 2019-01-29 02:16

The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.

int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...

Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:

int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
    int result = parsed + 2;
    string add = result.ToString();
    // Use add here    
}
else
{
    // Indicate failure to the user; prompt them to enter an integer.
}
查看更多
三岁会撩人
7楼-- · 2019-01-29 02:16
int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
    String add = (intValue + 2).ToString();
}

I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)

查看更多
登录 后发表回答