'Is there a way to dynamically change the text of a textBox in Visual Studio with C# so that the value is a sum of values from other textboxes?

I need to have a text box that dynamically changes as values in other text boxes are being changed, and the value (would be an integer converted to string) of the "Total" textbox has to have the sum of the other values. Is there a way to do this without having to create a TextChanged event for each of the other textboxes?



Solution 1:[1]

Should be something like

Label1.text= textbox1.value + textbox2.value + textbox3.value +.....

Solution 2:[2]

I'm assuming that you don't want to create TextChanged event handlers for each TextBox because it is a tedious job. There's a way to make it easy.

Start with a field like this:

private TextBox[] textBoxes = null;

Then you can set up all of the TextChanged event handlers like this:

textBoxes = new []
{
    textBox1, textBox2, textBox3,
    textBox4, textBox5,
};

foreach (var tb in textBoxes)
{
    tb.TextChanged += (_, _) => UpdateTotal();
}

Now the UpdateTotals can be defined any way you want. Here's my version:

private void UpdateTotal()
{
    var value =
        textBoxes
            .Select(x =>
                double.TryParse(x.Text, out double value)
                    ? value
                    : 0.0)
            .Sum();
            
    textBoxTotal.Text = value.ToString();
}

Solution 3:[3]

In Visual studio, go to Form1.cs[Design] and leftclick a textbox once, then, on the right hand lower side, click the lightning that says events. Search for TextChanged and type in how you would like the event to be named (e.g. textBox1_TextChanged). on hitting enter, you should automatically be sent to Form1.cs, where a new void was created. There, insert the code proposed by Stefanovici (although change textbox1.value to textbox1.text) and rinse and repeat for each textbox

private void textBox1_TextChanged(object sender, EventArgs e) //should automatically be created
{
    Label1.text= textbox1.text + textbox2.text + textbox3.text +.....
}

You can also bind multiple textboxes to the same event. Naming the event identical for every textbox will call the event when either textbox was changed, reducing the amount of code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefanovici
Solution 2
Solution 3 123 456 789 0