The textbox will only accept numbers and only one decimal point.
For example the textbox contains "12345.56". When the period is pressed a second time on the keyboard it must not appear in the textbox because the textbox already contains a period.
[0-9]+(\.[0-9][0-9]?)?
Go with regular expressions.
hande KeyPress event and assuming its windows
void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '.' )
{
if (richTextBox1.Text.Contains('.'))
e.Handled = true;
}
}
**//Only numeric with Two decimal place comes in textbox and if user want to enter decimal again or space it will not allowed.**
if ((e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || e.Key == Key.Decimal || e.Key == Key.OemPeriod))
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1, e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) + strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Key.A && e.Key <= Key.Z ||
e.Key == Key.Space)
{
e.Handled = true;
}
if (Keyboard.Modifiers == ModifierKeys.Shift && e.Key == Key.OemPeriod)
{
e.Handled = true;
}
private bool isValueEnteredExceed100(string textBoxValue, string inputText)
{
var countPeriod = textBoxValue.Count(x => x.ToString().Equals("."));
if (countPeriod <= 1)
{
bool isValidNumber = AreAllValidNumericChars(inputText);
if (isValidNumber == true || inputText == ".")
{
double enterdValue;
bool returnValue = false;
if (textBoxValue != string.Empty || textBoxValue != "")
{
enterdValue = Convert.ToDouble(textBoxValue);
if (enterdValue > 0 && enterdValue <= 100)
{
returnValue = true;
}
}
return returnValue;
}
else
{
return isValidNumber;
}
}
else
{
return false;
}
}
private void AcceptedFromTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
string textBoxValue = AcceptedFromTextBox.Text + e.Text;
if (textBoxValue == ".")
{
textBoxValue = "0" + e.Text;
AcceptedFromTextBox.Text = textBoxValue;
}
e.Handled = !isValueEnteredExceed100(textBoxValue, e.Text);
AcceptedFromTextBox.SelectionStart = AcceptedFromTextBox.Text.Length;
}
private bool AreAllValidNumericChars(string str)
{
Regex regex = new Regex(#"[0-9]$");
return regex.IsMatch(str);
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Code on Keypress event of textbox
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
Related
I want to validate TextBox to allow only 1 decimal point and up to 2 decimal places after it. For number validate only, i am using InputScope="Number", but it can not avoid pasting letters, so i need any validation for paste too (or just disable pasting). For example the user must be able to insert numbers like 23, 23.1, 23.12 and NOT 23.123, 23.1.2 etc.
private void tb1_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9 || e.Key == Windows.System.VirtualKey.Decimal || e.Key == Windows.System.VirtualKey.GamepadY)
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1, e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) + strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && e.Key == Windows.System.VirtualKey.Decimal)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Windows.System.VirtualKey.A && e.Key <= Windows.System.VirtualKey.Z ||
e.Key == Windows.System.VirtualKey.Space)
{
e.Handled = true;
}
}
I want a Decimal Point in an Integer. If decimal Point is not there it shows Error Message.
Sir, The following code is written in User Control Text Box.The maximum Length given by the user When he access the user control.
The following code is restricts the user to enter the Decimal point after the maximum length.
Please the run the code Sir,
public virtual int MaximumLength { get; set; }
private void txtCurrency_KeyPress(object sender, KeyPressEventArgs e)
{
txtCurrency.MaxLength = MaximumLength + 3;
int dotIndex = txtCurrency.Text.IndexOf('.');
if (e.KeyChar != (char)Keys.Back)
{
if (char.IsDigit(e.KeyChar))
{
if (dotIndex != -1 && dotIndex < txtCurrency.SelectionStart && txtCurrency.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
else if (txtCurrency.Text.Length == MaximumLength)
{
if (e.KeyChar != '.')
{ e.Handled = true; }
}
}
else
{
e.Handled = e.KeyChar != '.' || dotIndex != -1 || txtCurrency.Text.Length == 0 || txtCurrency.SelectionStart + 2 < txtCurrency.Text.Length;
}
}`enter code here`
decimal myValue = 12.4m;
int value = 0;
if (myValue - Math.Round(myValue) != 0)
{
throw new Exception("Has a decimal point");
}
else
{
value = (int)myValue;
}
You can use the RegularExpressions
private void textBox2_Validating(object sender, CancelEventArgs e)
{
Regex r = new Regex(#"^\d+.\d{0,1}$");
if (r.IsMatch(textBox2.Text))
{
MessageBox.Show("Okay");
}
else
{
e.Cancel = true;
MessageBox.Show("Error");
}
}
UPDATE:
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.'
&& (textBox2).Text.IndexOf('.') > -1) //Allow one decimal point
e.Handled = true;
}
I want textbox validation for allowing only one . value and only numbers. Means my textbox value should take only numerics and one . value. Value should be like 123.50.
I am using a code for adding .oo or .50 value at end of my value.
My code is
double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");
It is taking all the keys from keyboard, but I want to take only numbers and one . value.
Add a Control.KeyPress event handler for your textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dotIndex = textBox1.Text.IndexOf('.');
if (char.IsDigit(e.KeyChar)) //ensure it's a digit
{ //we cannot accept another digit if
if (dotIndex != -1 && //there is already a dot and
//dot is to the left from the cursor position and
dotIndex < textBox1.SelectionStart &&
//there're already 2 symbols to the right from the dot
textBox1.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
}
else //we cannot accept this char if
e.Handled = e.KeyChar != '.' || //it's not a dot or
//there is already a dot in the text or
dotIndex != -1 ||
//text is empty or
textBox1.Text.Length == 0 ||
//there are more than 2 symbols from cursor position
//to the end of the text
textBox1.SelectionStart + 2 < textBox1.Text.Length;
}
}
You may do it through designer or in your constructor like this:
public Form1()
{
InitializeComponent();
//..other initialization
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
I have also added several checks to ensure, that you could insert digits not only in the end of the text, but in any position. Same with a dot. It controls that you have not more than 2 digits to the right from the dot. I've used TextBox.SelectionStart Property to get the position of the cursor in the textbox. Check this thread for more info about that: How do I find the position of a cursor in a text box?
Simplly in keyPress event of your textBox you could do this ...
e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
try this one
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 == '.'
&& textBox1.Text.IndexOf('.') > -1)
e.Handled = true;
}
try this code and just replace what you want input type 'validinpu' string.
try
{
short charCode = (short)Strings.Asc(e.KeyChar);
string validinput = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789 .";
if (Strings.InStr(validamt, Conversions.ToString(Strings.Chr(charCode)), Microsoft.VisualBasic.CompareMethod.Binary) == 0)
{
charCode = 0;
}
if (charCode == 0)
{
e.Handled = true;
}
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
// To disallow typing in the beginning writing
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Also try this short one
e.Handled = (!(e.KeyChar == (char)Keys.Back || e.KeyChar == '.')); //allow dot and Backspace
e.Handled = (e.KeyChar == '.' && TextBox1.Text.Contains(".")); //allow only one dot
this example only allow one dot and backspace
if (textBox.Text!="")
{
string txt = textBox.Text;
if (e.KeyChar.ToString().Any(Char.IsNumber) || e.KeyChar == '.')
{
textBox.Text = rate;
}
else
{
MessageBox.Show("Number Only", "Warning");
textBox.Text = "";
}
}
My tested code
if(e.KeyChar.Equals('\b'))
{
e.Handled = false;
}
else
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
else
// only allow one decimal point
if (e.KeyChar == '.'
&& textBox1.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
I am using the following code to take only digits from user and only one decimal point , that is working fine for me on KeyPress Event :
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
Now I want to Limit the numbers/Digits after the decimal/dot i.e 35.25468, means it take only 6 numbers/digits after the dot/decimal.
Update me !
private void price_tb_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;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
}
This code will help you. It takes only one decimal place and two digit after one decimal place and you can change it accordingly.
you can add an additional check like this
TextBox textBox = (TextBox) sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >=3)
{
e.Handled = true;
}
Note, the Substring will include the '.' and hence the check is >=3.
On the keypress event, and or validate event, count the number of chars after decimal point. On key press, suppress it. on validate, remove extra decimal places. Make sure you're getting the decimal point char from NumberFormatInfo, not all cultures use '.', ie. in France, their decimal point is actually a comma
On keypress, format the string and set the textBox.Text to the formatted string.
TextBox.Text = String.Format("{0:N3"}", textBox.Text)
This particular format cuts off the number at the 3rd decimal.
I had textBox.SelectionLength == 0 to allow the modification of selected text:
private void price_tb_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') {
e.Handled = true;
}
TextBox textBox = (TextBox)sender;
// only allow one decimal point
if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1) {
e.Handled = true;
}
if (!char.IsControl(e.KeyChar) && textBox.SelectionLength == 0) {
if (textBox.Text.IndexOf('.') > -1 && textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3) {
e.Handled = true;
}
}
}
The issue I have with the answer of Both FM is that you cannot edit the text when you have entered a decimal place and two decimals.
This code also takes a minus amount.
private void TextBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
// OK, but not more than 2 after the [.]
if (((TextBox)sender).Text.Contains('.'))
{
if (((TextBox)sender).Text.IndexOf('.') + 2 < ((TextBox)sender).Text.Length)
{
if (((TextBox)sender).SelectionStart > ((TextBox)sender).Text.IndexOf('.'))
{
e.Handled = true;
}
}
}
}
else if (char.IsControl(e.KeyChar))
{
// Always OK
}
else if (e.KeyChar == '.' && !((TextBox)sender).Text.Contains('.'))
{
// First [.] == OK
}
else if (e.KeyChar == '-' && !((TextBox)sender).Text.Contains('-'))
{
// First [-] == OK
}
else
{
e.Handled = true;
}
}
private void TextBoxAmount_KeyUp(object sender, KeyEventArgs e)
{
if (((TextBox)sender).Text.Contains('-'))
{
((TextBox)sender).Text = $"-{((TextBox)sender).Text.Replace("-", string.empty)}";
}
}
On the text box, it should allow the user to enter only six decimal places. For example, 1.012345 or 1,012345.
If seven decimal places are tried, the entry should not be allowed.
Please refer to the below code.
private void textBox1_KeyDown_1(object sender, KeyEventArgs e)
{
bool numericKeys = (
( ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)) &&
e.Modifiers != Keys.Shift) ||
e.KeyCode == Keys.OemMinus ||
e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Decimal ||
e.KeyCode == Keys.Oemcomma
);
bool navigationKeys = (
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Home ||
e.KeyCode == Keys.End ||
e.KeyCode == Keys.Tab);
bool editKeys = (e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Back);
TextBox aTextbox = (TextBox)sender;
aTextbox.Text = "2,33333";
if (!string.IsNullOrEmpty(aTextbox.Text))
{
double maxIntensity;
string aTextValue = aTextbox.Text;
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
MessageBox.Show("the value is {0}", aText);
string[] args = aText.Split('.');
if (numericKeys)
{
bool handleText = true;
if (args.Length > 2)
{
handleText = false;
}
else
{
if (args.Length == 2 && args[1] != null && args[1].Length > 5)
{
handleText = false;
}
}
if (!handleText)
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
}
}
if (!(numericKeys || editKeys || navigationKeys))
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
To achieve the culture neutrality, the text value is converted to double first and then
the double value is converted to string.
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
}
Splitting the strings to separate the real part and mantissa part (both are stored are strings), then I check the length of the mantissa part. If the length of the string is more than 5, I'd like to suppress the key.
Is there aother approach to do this?
I've had luck with code similar to the following:
public class RegexMaskedTextBox : TextBox
{
private Regex _regex = new Regex(string.Empty);
public string RegexPattern
{
get { return _regex.ToString(); }
set { _regex = new Regex(value); }
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
string sNewText = this.Text;
string sTextToInsert = e.KeyChar.ToString();
if (this.SelectionLength > 0)
{
sNewText = this.Text.Remove(this.SelectionStart, this.SelectionLength);
}
sNewText = sNewText.Insert(this.SelectionStart, sTextToInsert);
if (sNewText.Length > this.MaxLength)
{
sNewText = sNewText.Substring(0, this.MaxLength);
}
e.Handled = !_regex.IsMatch(sNewText);
base.OnKeyPress(e);
}
}
I think I would solve this by using regular expressions. On the key down event you can check the regex.
Maybe you want to check this out: Regular expression for decimal number