C#. How to use pass multiple text boxes into metho

2019-08-11 03:14发布

问题:

my first post here.

I'm building a calculator that takes user input via text box and converts to a double and passes those numbers into a custom class that contains a formula(the answer is converted back to a string once complete). I have everything working, but I would like the label with the answer to automatically update once the text boxes are filled out. The label text output is correct once clicked on.

heres the code I have for the label so far...

    private void lblUtil1_Click(object sender, EventArgs e)
    {

        dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
        double UtilRounded1 = Math.Round(dblUtil1 * 100);
        lblUtil1.Text = UtilRounded1.ToString() + "%";
    }

Is there something that can detect if all the pertinent fields are completed or will this require a loop? I greatly appreciate all help and look forward to being a part of this community!

growthtek

回答1:

One approach would be to make this:

private void lblUtil1_Click(object sender, EventArgs e)
{
    dblUtil1 = Tinseth.Bigness(dblSG) * Tinseth.BTFactor(dblBT1);
    double UtilRounded1 = Math.Round(dblUtil1 * 100);
    lblUtil1.Text = UtilRounded1.ToString() + "%";
}

a shared method:

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

and get rid of the Click event. Then consume the text boxes Validated event:

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

Now hook all of the text boxes Validated events up to this same handler. Now when the user leaves the text box, it will calculate automatically.

The Validated event could just as easily be the TextChanged event as well. That will calculate every time they type a number. But that's probably too frequent.



回答2:

Create one function that does the calculation then bind that function to the changed event on all the textboxes.



回答3:

I would not run the calculation every time as Michael or Measuring suggested.

Instead, just put a few if statements in your click event that test to see if the required boxes have values. If they don't, then show a message saying they need to fill it out.

Something like:

if (String.IsNullOrEmpty(TextBox1.Text)) {
    MessageBox.Show("TextBox1 is empty");
    return;
}


标签: c# labels