C# winform minus 2 textboxs show answer in 3rd in reverse order

Booney 166 Reputation points
2021-09-15T21:40:15.82+00:00

This should be easy to fix but I cant fig it out.
I have 3 textboxes one below the other as a example. I tried textbox change

It works fine if I enter in order but if the user is out of order the math is wrong.
Is there a work around?

TXT1 - TXT2 = Correct answer
TXT2 - TXT1 = Wrong answer

private void CalcTotal(object sender, EventArgs e)
        {

            if (int.TryParse(txt_BackedOut.Text, out int i) && int.TryParse(txt_TOTAL.Text, out int j) && int.TryParse(txt_Online.Text, out int t))
                textBox1.Text = (j - i - t).ToString();

        }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,862 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,463 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,286 Reputation points
    2021-09-15T23:34:24.677+00:00

    Needs some polishing up, see if this might work for you.

    132495-figure1.png

    public partial class Form1 : Form  
    {  
        private readonly List<TextBox> _textBoxes = new List<TextBox>();  
        public Form1()  
        {  
            InitializeComponent();  
        }  
      
        private void Form1_Load(object sender, EventArgs e)  
        {  
            _textBoxes.Add(textBox1);  
            _textBoxes.Add(textBox2);  
            _textBoxes.Add(textBox3);  
      
            _textBoxes.ForEach(textbox => textbox.TextChanged += OnTextChanged);  
        }  
      
        private void OnTextChanged(object sender, EventArgs e)  
        {  
            if (_textBoxes.All(texbox => int.TryParse(texbox.Text, out _)))  
            {  
                int.TryParse(textBox1.Text, out var v1);  
                int.TryParse(textBox2.Text, out var v2);  
                int.TryParse(textBox3.Text, out var v3);  
      
                textBox4.Text = (v1 + v2 - v3).ToString();  
      
            }  
            else  
            {  
                textBox4.Text = "";  
            }  
        }  
    }  
    

2 additional answers

Sort by: Most helpful
  1. P a u l 10,406 Reputation points
    2021-09-15T21:52:48.097+00:00

    Do you mean if you enter values in your textboxes in different order? (i.e. BackedOut, Total, Online -> Online, Total, BackedOut)


  2. P a u l 10,406 Reputation points
    2021-09-15T22:20:04.047+00:00

    You mean like?:

    textBox1.Text = (-j - i - t).ToString();