Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only allow two digits after decimal in textbox?

Tags:

c#

winforms

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; 
    } 
}
like image 702
user710502 Avatar asked Apr 01 '12 19:04

user710502


2 Answers

Just add:

if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) {
   e.Handled = true;
}

to the end of your function

like image 75
aquinas Avatar answered Sep 19 '22 12:09

aquinas


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;
}
like image 39
Scott Avatar answered Sep 21 '22 12:09

Scott