Setting Textbox for Currency

Asked

Viewed 672 times

0

I’m trying to set up a TextBox in a Windowsform to display the value of the field in the currency format. I can only do that in the Enter event of the field with the following code:

private void valorTextBox_Enter(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    txt.Text = double.Parse(valorTextBox.Text).ToString("C2");
}

How do I make it happen at the event Form_Load and in the navigation of records?

  • https://answall.com/questions/28129/stilo-moeda-numa-textbox-em-winforms I think this response should help.

1 answer

1

Create a método:

public void ToMoney(TextBox text, string format = "C2")
{
    double value;
    if (double.TryParse(text.Text, out value))
    {
        text.Text = value.ToString(format);
    }
    else
    {
        text.Text = "0,00";
    }            
}

and in the Form_Load:

private void Form1_Load(object sender, EventArgs e)
{
    ToMoney(textBox1, "N2");
}

About where to call in the navigation method, check on componente (or code) where there is a method indicating that there was a navigation event, if by chance, put in your question, I can tell you where to call

Observing: your code had a problem, does not check if the value is a number and this can bring errors.

You could also create an extension method by following this class:

public static class TextMoney
{
    public static void ToMoney(this TextBox text, string format = "C2")
    {
        double value;
        if (double.TryParse(text.Text, out value))
        {
            text.Text = value.ToString(format);
        }
        else
        {
            text.Text = "0,00";
        }
    }
}

and in the Form_Load simplifying:

private void Form1_Load(object sender, EventArgs e)
{
    textBox1.ToMoney(); 
    ou //textBox1.ToMoney("N2"); 
}

Links

  • 1

    Dear Virgil, thank you so much for answering. I appreciate your help. I will follow your suggestions and see what you give. A big hug. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.