As Crono stated in another answer, a MaskedTextBox
is the best solution. But if you really want to add the constraints and formatting to your text box you could just parse the text into a decimal
, then override the comma key altogether and only allow one decimal.
This is a bit hacked together but should achieve what you are looking for:
First create the event handler to not allow comma entry and only allow one decimal point
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//Just don't let them type commas - We will format after the TextBox is left
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar == ',')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Then create a little helper method to parse the value of your TextBox to a decimal
private decimal GetValueFromTextBox(string input)
{
input = System.Text.RegularExpressions.Regex.Replace(input, @"[,$%]", String.Empty);
//Could use Try parse here for better handling
decimal output = Convert.ToDecimal(input);
return output;
}
Then just call the function from your TextBox_Leave
event:
private void textBox1_Leave(object sender, EventArgs e)
{
var value = GetValueFromTextBox(textBox1.Text);
textBox1.Text = value.ToString("c");
}
This will format the value in Currency format with the proper comma placement enforcing only one decimal point as well. Again NOT THE BEST SOLUTION (use a MaskedTextBox) but it will work for a normal TextBox
control.