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