I have a textbox where the user enters a number, but how can i make it so that if they type the '.' after it it only allows 2 decimal places?
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
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;
}
}
Just add:
if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) {
e.Handled = true;
}
to the end of your function
Just wanted to point out that the accepted answer will not allow you to enter any numbers BEFORE the decimal point either once that criteria has been met.
None of the other current examples will work either because they are not getting cursor position
If you still want to use keypress event you could re-factor your code as follows:
string senderText = (sender as TextBox).Text;
string senderName = (sender as TextBox).Name;
string[] splitByDecimal = senderText.Split('.');
int cursorPosition = (sender as TextBox).SelectionStart;
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& (e.KeyChar != '.'))
{
e.Handled = true;
}
if (e.KeyChar == '.'
&& senderText.IndexOf('.') > -1 )
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar)
&& senderText.IndexOf('.') < cursorPosition
&& splitByDecimal.Length > 1
&& splitByDecimal[1].Length == 2)
{
e.Handled = true;
}
Alternatively, use TextChanged event and do the following and it will work:
string enteredText = (sender as TextBox).Text;
int cursorPosition = (sender as TextBox).SelectionStart;
string[] splitByDecimal = enteredText.Split('.');
if(splitByDecimal.Length > 1 && splitByDecimal[1].Length > 2){
(sender as TextBox).Text = enteredText.Remove(enteredText.Length-1);
(sender as TextBox).SelectionStart = cursorPosition - 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With