I have a textbox in C# where the user can enter only decimal numbers (negative and positive).
I don't want to use MaskedText Box, I would rather implement this using the keypress event to validate inputs.
How can I achieve this?
Thanks,
*********EDIT*********++
private void mytextbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != '.' &&e.KeyChar!='-'))
{
e.Handled = true;
}
if (e.KeyChar == '.')
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
if (e.KeyChar=='-' && (sender as TextBox).SelectionStart > 0)
{
e.Handled = true;
}
}
TryParse for the various numeric types will tell you if the input is valid. For example, if you want to use a double:
private void OnKeyPress(...)
{
double parsedValue = 0;
if (double.TryParse(MyTextBox.Text, out parsedValue)
{
//Valid number entered, value in parsedValue
}
else
{
//Invalid number entered
}
}
This answer has a lot of other ways to accompish this: How do I make a textbox that only accepts numbers?
Related
Until today for validate what data I insert in the text box I used this following code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
It works perfectly fine, but when I try to select all, or copy or paste and also insert "-" for negative float it's just crash, how can I validate this type of "KeyPress"?
Try this, it should do the trick:
private void txtFloat1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46 && e.KeyChar != 45 && e.KeyChar != 3 && e.KeyChar != 22 && e.KeyChar != 1))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
I need to make a textbox to accept only positive integers but I was not successful.
In my Keypress event in entered this codes:
if (char.IsDigit(e.KeyChar) || e.KeyChar == (int)Keys.Back || e.KeyChar == (int)Keys.Delete)
{
//// To allow positive integers
}
else
{
e.Handled = true;
}
//This is used for enter button
int d = Convert.ToInt32(e.KeyChar);
if (d == 13 && MyExamPeriod_tx.Text != "")
{
}
Users have a textbox where they have to either enter a 0 or a value from 0.0001 to 0.9999.
What regex can I use here? I have looked at other examples but don't see anything like this one.
I'd say this is quite an effective solution. It allows for any strings entered that is either just a '0' or strings with '0.' followed by up to 4 of any digit.
Regex myRegex = new Regex("^(?:(?:0)|(?:0.[0-9]{1,4}))$");
Console.WriteLine("Regex: " + myRegex + "\n\nEnter test input.");
while (true)
{
string input = Console.ReadLine();
if (myRegex.IsMatch(input))
{
Console.WriteLine(input + " is a match.");
}
else
{
Console.WriteLine(input + " isn't a match.");
}
}
Here's a list of tests...
Try this one:
/(0)+(.)+([0-9])/g
Also see thing link that might helps you build you won expreession.
http://regexr.com/
Try this, it will do the work but I was not tested for all cases.
Regex _regex = new Regex("^[0]+(.[0-9]{1,4})?$");
if (input == "0" || _regex.IsMatch(input))
{
//Match
}
else
{
//Does not match
}
Note: input is a string, in your case Textbox.Text!
This is ready to use KeyPress event handler of TextBox control. It will prevent any input, except numeric between 0.0001 and 0.9999:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//Only one dot is possible
if ((sender as TextBox).Text.Contains('.') && (e.KeyChar == '.')) e.Handled = true;
//Only numeric keys are acceptable
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) e.Handled = true;
//Only one zero in front is acceptable, next has to be dot
if (((sender as TextBox).Text == "0") && (e.KeyChar == '0')) e.Handled = true;
double value = 0;
string inputValue = (sender as TextBox).Text + e.KeyChar;
if ((sender as TextBox).Text.Length > 0)
{
//Just in case parse input text into double
if (double.TryParse(inputValue, out value))
{
//Check if value is between 0.0001 and 0.9999
if (value > 0.9999) e.Handled = true;
if (((sender as TextBox).Text.Length > 4) && (value < 0.0001)) e.Handled = true;
}
}
else if (e.KeyChar != '0')
{
e.Handled = true;
}
}
Currently I have this code for preventing character entering, and more than one decimal place,
but how to prevent the first character being a decimal?
private void textBoxNoLetters_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
else if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
Below is your code, modified to handle a decimal separator typed fist, additionally the decimal separator character of your system is obtained to assist in localizing your application.
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != decimalChar)
{
e.Handled = true;
}
else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.IndexOf(decimalChar) > -1))
{
e.Handled = true;
}
else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.Length == 0))
{
e.Handled = true;
}
How can I restrict the user from entering anything, in a text box, other than a value between 0 to 99.99
My code seems to be working but, it will allow any number to be entered. It will allow only number and a dot once. But it will still allow a value greater than 99.99
Below my code:
private void InputMargin_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
// allow only number and dot
if ( ! char.IsControl(e.KeyChar)
&& ! char.IsDigit(e.KeyChar)
&& e.KeyChar != '.'
|| (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
)
{
//e.Handled = true;
double margin;
double.TryParse((sender as TextBox).Text, out margin);
if (margin >= 0 && margin <= 99.99)
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
catch
{
e.Handled = false;
}
}
why not use NumericUpDown control with DecimalPlaces property set to 2.
no need to add any additional coding like on textbox.
why are you using `&& e.KeyChar != '.' because doing so doesnot accepts '.' .just delete this because you have also used (sender as TextBox).Text.IndexOf('.') > -1 this accepts only one '.' in the whole textfield so the Right if statement will be.
if ( ! char.IsControl(e.KeyChar)
&& ! char.IsDigit(e.KeyChar)
|| (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
)
{
//Your Code
}