Configure TextBox for Currency

0

I am trying to set a TextBox in a WindowsForm to display the value of the field in currency format. I can only make this happen 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 this happen in the Form_Load event and in the navigation of the records?

    
asked by anonymous 25.09.2016 / 10:24

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 Form_Load :

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

Where to call in the navigation method, check the componente (or code) where you have a method that indicates that there was a navigation event, if you put it in your question, I can tell you where to call

Note: Your code had a problem, it does not check if the value is a number and this can cause errors.

You could also create an extension method 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 Form_Load simplifying:

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

Links

25.09.2016 / 16:06