Question Looping of if condition not working correctly

shsh_shah

Member
Joined
Aug 29, 2012
Messages
5
Programming Experience
Beginner
Hello,

When i use below code - App launches and when entering values it loops two times through my if(tb != null) function - Any idea please?
And then somehow my total text box same value twice.

C#:
public Form()
        {
            InitializeComponent();
            TextBox[] tbs = new TextBox[] { monTxtBox, tuesTxtBox, wedTxtBox, thurTxtBox, frdtxtBox };
            foreach (var c in tbs)
            c.TextChanged += new EventHandler(textBoxes_TextChanged); //create a common event for all textBoxes
        }
        
        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)
               //     totalTimetxtBox.Text = Convert.ToDecimal(tb.Text.Replace(",",".").ToString())+temp;
                     totalTimetxtBox.Text = tb.Text+temp;
            else
                MessageBox.Show("Please enter the number between 0 and 1.");
                }
        else
            MessageBox.Show("Please enter a decimal value only!");
            }
        }
 
Why are you writing code yourself to attach an event handler to a control? You should be attaching the event handler in the designer. If you're saying that the event handler is being invoked twice then I'd suggest that you actually have attached the event handler in the designer. If you've attached the event handler once in the designer and once in code then of course it gets invoked twice.
 
Back
Top Bottom