Search code examples
c#winformstextchanged

Auto refresh labels as text boxes text input data into method


Here is my method that I' am trying to have automatically refresh my label. When I have my label as a click event...the answer refreshes and is correct.

private void Calculate()
{
    dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
    double UtilRounded1 = Math.Round(dblUtil1 * 100);
    strUtil1 = UtilRounded1.ToString() + "%";
}

Here is the Validated label event that does not update when text is changed in my text boxes.

private void lblUtil1_Validated(object sender, EventArgs e)
{
    Calculate();
}

If this is correct...what am I missing? is there something I need to do on the text boxes that will trigger validation?

I have also tried a text changed event that yields the error cannot implicitly convert type void(or any type for that matter) to EventHandler. Here is the code.

private void lblUtil1_TextChanged(object sender, EventArgs e)
{
    lblUtil1.TextChanged += Calculate();
}

Any help is appreciated! I've been banging my head on my keyboard for a day now.


Solution

  • First at all, you have to handle events for the TextBox that you input value to calculate, such as when you change vale in the TextBox or validate it.

    So if you have textBox1 then you should have this handling (trigger when value in textBox1 is changed)

     private void textBox1_TextChanged(object sender, EventArgs e)
     {
         lblUtil1.Text = Calculate();
     }
    

    I assume that you want to display value in strUtil1 at the label lblUtil1, so you have to change your Calculate method like this

     private string Calculate()
     {
        dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
        double UtilRounded1 = Math.Round(dblUtil1 * 100);
        strUtil1 = UtilRounded1.ToString() + "%";
    
        return strUtil1;
     }
    

    EDITED

    This is a sample code for validate the required TextBoxes.

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        if (textBox1.Text == "") 
        {
            e.Cancel = true;
            lblUtil1.Text = "textBox1 is required!";
        }
    }