Add textbox values when leaving the field

Asked

Viewed 1,208 times

2

I have a form with three TextBoxes where the user will enter any value and a Label where I want to show the result of the sum of these values.

However, I would like to add up the contents of these TextBoxes without having to click a button. I mean, as long as I’m filling in the TextBoxes, the values are being added up and the sum is shown in the Label.

  • you have done the routine that performs the calculation? you can call it in the output of the last textbox, in the event onExit() or similiar.

  • This way it would perform the routine after the user click off txtbox?

  • Textchanged() is also a good idea... but think that if the text is null, without text, when turning to integer, it will give an error, then initially it is recommended.

  • This is all set, if it is equal to null it considers 0 . then this textchanged method will execute qnd it click off ?

1 answer

0

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void fazOqVcQuer()
    {
        try
        {
            label1.Text =
            (Convert.ToDecimal(textBox1.Text)
            +
            Convert.ToDecimal(textBox2.Text)
            +
            Convert.ToDecimal(textBox3.Text)).ToString();
        }
        catch (Exception)
        {
        }  
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        fazOqVcQuer();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        fazOqVcQuer();
    }

    private void textBox3_TextChanged(object sender, EventArgs e)
    {
        fazOqVcQuer();
    }
}

Hello friend. There are several ways to do this. Since you are starting, understand this code "well" simple. replace the values "textBox1", "textBox2" and "textBox3" by their name, etc

  • No need to declare three events that do the same thing, this code is very repetitive. You can use the same event for several TextBoxes different.

  • Another thing, don’t use that pad catch empty. Or you use the catch for really treat exceptions or you let the error "pop".

  • He mentioned having just started programming.

  • So I should show you the right way to do things.

  • Aahh got it. Make a method that adds the two txt box (converting to int for example) and have the result shown in the label. And use the event text_changed( q would qnd txtbox n is selected) to call the method. Eh that? And no catch could put " type only numbers" eh folks?

  • Textchanged - each modified/inserted character in the textbox will trigger the event. E in catch, yes you can put this.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.