Add numbers in c#

后端 未结 7 1012
难免孤独
难免孤独 2020-12-21 12:19

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

7条回答
  •  既然无缘
    2020-12-21 12:56

    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.
    }
    

提交回复
热议问题