Search code examples
c#.netwinformsnumericupdown

Numericupdown value always sums 1 number less


private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    try
    {
        textBox2.Text = Convert.ToString(Convert.ToInt32(textBox1.Text.Trim()) + Convert.ToInt32(numericUpDown1.Text.Trim()));
    }
    catch (Exception)
    { }
}

The sum of a textbox and a numericupdown box is always varying by 1 digit when using up down. When using botton/ value changed in numericupdown.

Init Initially starts with 1 adding no value in below textbox when changed.

enter image description here When changed by numeridown it changes like this :


Solution

  • You need to use the NumericUpDown.Value property, not its Text property.
    It's also better if you validate the value entered in the TextBox. You can use int.TryParse() for this:

    if (int.TryParse(textBox1.Text, out int inputValue)
    {
        textBox2.Text = $"{inputValue + numericUpDown1.Value};
    }
    

    String interpolation ($"{ }") is available from C# 6.0+.
    Use [int].ToString() if you're using a previous version:

    textBox2.Text = (inputValue + numericUpDown1.Value).ToString();
    

    If the out variable declaration (C# 7.0+) is not available, declare the variable before-hand:

    int inputValue = 0;
    if (int.TryParse(textBox1.Text, out inputValue)
    {
        textBox2.Text = $"{inputValue + numericUpDown1.Value};
    }
    

    For Visual Studio 2012/2013, C# 5.0:

    int inputValue = 0;
    if (int.TryParse(textBox1.Text, out inputValue)
    {
        textBox2.Text = (inputValue + numericUpDown1.Value).ToString();
    }