Restricting the characters in the text box - c#

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

Related

How to validate TextBox to allow only 1 decimal point - Windows Phone 8

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;
}
}

Use two Key Events one after another in C#

I have 3 text-boxes in my C# Windows Form application for A, B and C respectively. Just like a simple scoring board.
What I want to do is when I press 'A' and then '1' the value in the text-box below should increment by 5 and when I press 'B' and then '1' the same should happen with the text-box below B and same as 'C'.
Just remember I don't want to use the combination keys. Below is the code for your reference:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vA = int.Parse(textBox1.Text);
vA += 5;
textBox1.Text = (String)vA.ToString();
}
}
if (e.KeyCode == Keys.B)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vB = int.Parse(textBox2.Text);
vB += 5;
textBox2.Text = (String)vB.ToString();
}
}
}
Considering you do NOT want to use combination keys, what you want to do is something similar to this (probably clean it up a little bit).
TextBox target;
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
target = textBox1;
}
if (e.KeyCode == Keys.B)
{
target = textBox2;
}
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
if(target != null)
{
int vA = int.Parse(target.Text);
vA += 5;
target.Text = (String)vA.ToString();
}
}
}
We can use a member variable to keep the value of last pressed key and use that variable inside KeyUp method to check the conditions.
public partial class Form1 : Form
{
Keys lastkeyPressed = Keys.Enter;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (lastkeyPressed == Keys.A)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vA = 0;
int.TryParse(textBox1.Text, out vA);
vA += 5;
textBox1.Text = (String)vA.ToString();
}
}
if (lastkeyPressed == Keys.B)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vB = 0;
int.TryParse(textBox2.Text, out vB);
vB += 5;
textBox2.Text = (String)vB.ToString();
}
}
if (lastkeyPressed == Keys.C)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vC = 0;
int.TryParse(textBox3.Text, out vC);
vC += 5;
textBox3.Text = (String)vC.ToString();
}
}
lastkeyPressed = e.KeyCode;
}
}

Validating the integer

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;
}

textbox validation for allow one " . " value c#

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;
}

How to accept only one decimal point in a textbox?

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;
}

Categories

Resources