BabyDoll
BabyDoll

Reputation: 265

Decimal values in textboxes

I need to allow only gps coordinate values in a textbox, the format will be 2 digits then a decimal point and 5 digits after the decimal. E.g. "28.98706".

How can I accomplish this? I would also appreciate if someone could explain the difference between using regex and regular expressions.

Upvotes: 2

Views: 129

Answers (3)

Selman Genç
Selman Genç

Reputation: 101681

Probably numericUpDown would be better. But here is a possible solution with TextBox:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
   if (char.IsControl(e.KeyChar)) return;

   if (e.KeyChar == '.' && textBox1.Text.Length < 2) e.Handled = true;

   if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.') e.Handled = true; // check for non-digit character

   if (textBox1.Text.Length == 2 && e.KeyChar != '.') e.Handled = true; // you should type dot '.'

   if (textBox1.Text.Length == 8) e.Handled = true;
}

Upvotes: 1

Robert Fricke
Robert Fricke

Reputation: 3643

Regex and regular expressions are the same thing. Use it to validate the user input to your pattern of allowed values.

Example:

if(!Regex.IsMatch("[0-9]+\.?[0-9]*", TextBox.Text)) 
    return false;

return true;

Upvotes: 0

Tarec
Tarec

Reputation: 3255

Don't use a textbox. Use NumericUpDown instead - it stores value in decimal format, allowing you to set decimal point precision.

Also regex = regular expression.

Upvotes: 4

Related Questions