Search code examples
c#winformssender

Trying to update one textbox from another and vice-versa C# Winforms


I have two textboxes on a Winform. The idea is to enter Fahrenheit in one box and have it present Celcius in the other as the user types, and vice versa.

I have it working fine using the 'Leave' method of the textbox but I was trying to use the TextChanged method to avoid having to click or press a button for the result.

The problem I have now is that when the first character is processed the focus moves to the second box, which fires the TextChanged method.

I've tried using the sender to enable an if() but the sender is now the destination box.

Any thoughts, please?

       private void TB_Fahrenheit_TextChanged(object sender, EventArgs e)
    {

        float C, F;

        if (TB_Fahrenheit.Text != "")
        {
            if (float.Parse(TB_Fahrenheit.Text) < 1.0F)
            {
                TB_Fahrenheit.Text = "0" + TB_Fahrenheit.Text;
            }

            F = float.Parse(TB_Fahrenheit.Text);
            C = ((F - 32) * 5) / 9;
            TB_Celcius.Text = C.ToString();
        }

    }

    private void TB_Celcius_TextChanged(object sender, EventArgs e)
    {
        float C, F;
        string SentBy = ((TextBox)sender).Name;

        MessageBox.Show(SentBy);
        return;

        if(SentBy != TB_Fahrenheit.Text)
        {

        if (TB_Celcius.Text != "")
        {
            if (float.Parse(TB_Celcius.Text) < 1.0F)
            {
                TB_Celcius.Text = "0" + TB_Celcius.Text;
            }

            C = float.Parse(TB_Celcius.Text);
            F = ((C * 9) / 5) + 32;
            TB_Fahrenheit.Text = F.ToString();
        }
        }

    }

    private void TB_Celcius_Enter(object sender, EventArgs e)
    {
        TB_Celcius.Clear();
        TB_Fahrenheit.Clear();
    }

    private void TB_Fahrenheit_Enter(object sender, EventArgs e)
    {
        TB_Celcius.Clear();
        TB_Fahrenheit.Clear();
    }

Solution

  • I would use a Boolean checker.You are changing the text of a text box that has a text changed event. You need to make sure it does nothing if the other box is currently being edited. My example

    private void setSliderValue(int currentAudioSecond)
    {
        valueFromTimer = true;
        //Do Stuff
        valueFromTimer = false;
    }
    

    Then when the value is changed on my slider control:

    private void sliderAudio_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        if (!valueFromTimer)
        {
            //Do stuff  
        }
    }
    

    I have to do this often when loading up a window, or form, I fill a combo box. To avoid the selected value/index changed to fire, I have to implement a flag like this.