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
}
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 blocked all key on keyboard excluding 1-9 and I have a problem how to enable comma?
My code:
private void textbox_KeyDown(object sender, KeyRoutedEventArgs e)
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9 || e.Key >= Windows.System.VirtualKey.NumberPad0 && e.Key <= Windows.System.VirtualKey.NumberPad9 || e.Key == Windows.System.VirtualKey.Decimal)
{
e.handled = false;
}
else
{
e.handled = true;
}
This code will allow only numbers and comma
if (!char.IsDigit(e.KeyChar) && e.KeyChar != ',')
{
e.Handled = true;
}
Alternative
if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != ',')
{
e.Handled = true;
}
try this...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if((e.KeyChar >= 48 && e.KeyChar <= 57) || (e.KeyChar >= 97 && e.KeyChar <= 105))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
According to the documentation for Virtual Key Codes you need OemComma which is 0xBC or (VirtualKey)188.
You can try this:
string keyInput = e.KeyChar.ToString();
if (Char.IsDigit(e.KeyChar))
{
// Digits are OK
}
else if (e.KeyChar == '\b')
{
// Backspace key is OK
}
else if (e.KeyChar == ',')
{
// Comma key is OK
}
else
{
// Swallow this invalid key and beep
e.Handled = true;
// MessageBeep();
}
First of all you have to remember that decimal mark ( either . or , ) has to be set up in the CultureInfo. If you're planning to release your application to the further audience I would recommend keeping this in mind.
Another thing is that your condition makes no sense :
// this has to be always true
e.Key >= Windows.System.VirtualKey.Number0
&&
e.Key <= Windows.System.VirtualKey.Number9
|| // above or below has to be true
e.Key >= Windows.System.VirtualKey.NumberPad0
&& // something from above has to be true and below has to be true
e.Key <= Windows.System.VirtualKey.NumberPad9
|| // or just decimal mark .. ?
e.Key == Windows.System.VirtualKey.Decimal
So proceeding with the code :
// check for the keys
if(
( // if numeric between 0 and 9
e.Key >= Windows.System.VirtualKey.Number0
&&
e.Key <= Windows.System.VirtualKey.Number9
)
|| // or
( // numeric from numpad between 0 and 9
e.Key >= Windows.System.VirtualKey.NumberPad0
&&
e.Key <= Windows.System.VirtualKey.NumberPad9
)
|| // or decimal mark
e.Key == Windows.System.VirtualKey.Decimal
)
{
// your logic
}
Remember that Windows.System.VirtualKey.Decimal will not return the decimal mark ( separator ) based on the CultureInfo but instead the decimal mark from the numpad.
If you want to use culture info ( international application ) you can find decimal mark in CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator and then compare the text input.
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;
}
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?
i am trying develop a code to restrict TextBox using C# to only allow numbers entry + comma(",") or dot(".") + only 2 numbers after dot or comma
So this way see possible numbers that can entry:
3213,04 = OK
3211,664 = Not
32.31 = OK
32.3214 = Not
334,,00 = Not
3247,.00 = Not
214.,00 = Not
32.. = Not
8465,0 = Ok
654.0 = Ok
Understood My goal ?
I developed code bellow
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtValormetrocubico.TextLength >= 0 && (e.KeyChar == (char)Keys.OemPeriod || e.KeyChar == (char)Keys.Oemcomma))
{
//tests
}
else
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf(',') > -1)
{
e.Handled = true;
}
}
}
This is auxiliary function I have written
private bool alreadyExist(string _text , ref char KeyChar)
{
if (_text.IndexOf('.')>-1)
{
KeyChar = '.';
return true;
}
if (_text.IndexOf(',') > -1)
{
KeyChar = ',';
return true;
}
return false;
}
This your key press event handler
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar='s';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (txtValormetrocubico.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (txtValormetrocubico.SelectionStart== 0 ) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(txtValormetrocubico.Text , ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (txtValormetrocubico.SelectionStart != txtValormetrocubico.Text.Length && e.Handled ==false)
{
// '.' or ',' is in the middle
string AfterDotString = txtValormetrocubico.Text.Substring(txtValormetrocubico.SelectionStart);
if (AfterDotString.Length> 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(txtValormetrocubico.Text ,ref sepratorChar))
{
int sepratorPosition = txtValormetrocubico.Text.IndexOf(sepratorChar);
string afterSepratorString = txtValormetrocubico.Text.Substring(sepratorPosition + 1 );
if (txtValormetrocubico.SelectionStart > sepratorPosition && afterSepratorString.Length >1)
{
e.Handled = true;
}
}
}
}
I think you need something like Masked Textbox control here you have some references
http://msdn.microsoft.com/en-us/library/kkx4h3az.aspx
http://www.c-sharpcorner.com/uploadfile/mahesh/maskedtextbox-in-C-Sharp/
Another way to do what you want is to use regular expressions
Well you can create a general function and call it on keypress event this code is a general instance.
validate_textBox is a general function
private void validate_textBox(TextBox _text, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar = 's';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (_text.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (_text.SelectionStart == 0) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(_text.Text, ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (_text.SelectionStart != _text.Text.Length && e.Handled == false)
{
// '.' or ',' is in the middle
string AfterDotString = _text.Text.Substring(_text.SelectionStart);
if (AfterDotString.Length > 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(_text.Text, ref sepratorChar))
{
int sepratorPosition = _text.Text.IndexOf(sepratorChar);
string afterSepratorString = _text.Text.Substring(sepratorPosition + 1);
if (_text.SelectionStart > sepratorPosition && afterSepratorString.Length > 1)
{
e.Handled = true;
}
}
}
}
Then you can call function like this code for each textbox you have in the form
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
validate_textBox(sender as TextBox, e);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
validate_textBox(sender as TextBox, e);
}
I don't know who is looking for this in 2021 but here is one solution overriding the ontextchange event! Cheers
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
String text = "";
Char[] chars = this.Text.ToString().ToCharArray();
int total_dots = 0;
int dot_pos = 0;
int char_pos = 0;
foreach (Char c in chars )
{
char_pos++;
if (Char.IsDigit(c))
{
if(dot_pos > 0) { //dot already exists
if (char_pos <= dot_pos + 2) //only accept two numbers after dot (3.99)
{
text += c.ToString();
}
}
else
{
text += c.ToString();
}
}
if(c == '.' || c == ',')
{
total_dots++;
if (char_pos > 1 && total_dots <=1) //only accept one dot and if the dot is not in first position
{
text += c.ToString();
dot_pos = char_pos;
}
}
}
this.Text = text;
this.SelectionStart = this.Text.Length;
}