C# convert random numbers in textBox to currency
private void textBox1_Validating(object sender, CancelEventArgs e)
{
string value;
NumberStyles style;
CultureInfo culture;
decimal currency;
value = textBox1.Text;
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-US");
if (!Decimal.TryParse(value, style, culture, out currency))
{
MessageBox.Show("Please enter a valid currency amount.", "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Error);
// prevent the textbox from losing focus
e.Cancel = true;
}
}
private void textBox1_Validated(object sender, EventArgs e)
{
string input = textBox1.Text.Trim();
if (input.StartsWith("$"))
{
string temp = input.Replace("$","");
string specifier = "C";
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
textBox1.Text = Decimal.Parse(temp).ToString(specifier, culture);
}
}