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
https://answall.com/questions/28129/stilo-moeda-numa-textbox-em-winforms I think this response should help.
– Marcelo Cardoso