Question Textfield not calculating all fields

shsh_shah

Member
Joined
Aug 29, 2012
Messages
5
Programming Experience
Beginner
hello,
I have below code and i am trying to get the values of all textboxes and then adding it in totaltextbox but currently it takes only current textbox and when it leaves to 2nd it forgets the first one.
Any help please?


C#:
private void textBoxes_TextChanged(object sender, EventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb != null)
            {
               decimal temp = 0;
                if (decimal.TryParse(tb.Text, out temp))
                {
                    if (temp > 1)
                        MessageBox.Show("Please enter the nnumber between 0 and 1.");
                }
            }
        }

        private void textBoxes_Leave(object sender, System.EventArgs e)
        {
            decimal total = 0;
            TextBox tb = sender as TextBox;
            if (tb != null)
            {
                decimal temp = 0;
                if (decimal.TryParse(tb.Text, out temp))
                {
                    total += temp;
                    totalTimetxtBox.Text = total.ToString();
                    
                }
            }
        }
 
private TextBox[] textBoxes;

public Form1()
{
    InitializeComponent();

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

private void textBoxes_Validating(object sender, CancelEventArgs e)
{
    var field = (TextBox) sender;

    if (field.TextLength > 0)
    {
        decimal number;

        if (!decimal.TryParse(field.Text, out number) || number < 0m || number > 1m)
        {
            field.SelectAll();
            field.HideSelection = false;
            MessageBox.Show("Please enter a number from 0 to 1.",
                            "Invalid Input",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            field.HideSelection = true;
            e.Cancel = true;
        }
    }
}

private void textBoxes_Validated(object sender, EventArgs e)
{
    var sum = textBoxes.Sum(tb => tb.TextLength == 0
                                      ? 0m
                                      : decimal.Parse(tb.Text));

    MessageBox.Show(sum.ToString(), "Total");
}
 
Back
Top Bottom