Add numbers in c#

后端 未结 7 993
难免孤独
难免孤独 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:46
    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();
    
    0 讨论(0)
  • 2020-12-21 12:48

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

    String add = (int.Parse(mytextbox.Text) + 2).ToString();
    
    0 讨论(0)
  • 2020-12-21 12:54

    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;
    
    0 讨论(0)
  • 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.
    }
    
    0 讨论(0)
  • 2020-12-21 13:02
    String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
    

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

    0 讨论(0)
  • 2020-12-21 13:05
    const int addend = 2; 
    string myTextBoxText = mytextbox.Text;
    var doubleArray = new double[myTextBoxText.ToCharArray().Length];
    for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
    {
        doubleArray[index] = 
            Char.GetNumericValue(myTextBoxText.ToCharArray()[index]) 
            * (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
    }
    string add  = 
        (doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();
    
    0 讨论(0)
提交回复
热议问题