C# Numeric Only TextBox Control [duplicate] - c#

This question already has answers here:
numeric-only textbox as a control in Visual Studio toolbox
(4 answers)
Closed 9 years ago.
I am using C#.NET 3.5, and I have a problem in my project. In C# Windows Application, I want to make a textbox to accept only numbers. If user try to enter characters message should be appear like "please enter numbers only", and in another textbox it has to accept valid email id message should appear when it is invalid. It has to show invalid user id.

I suggest, you use the MaskedTextBox: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx

From C#3.5 I assume you're using WPF.
Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.
For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.
Look up Binding on MSDN.

use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}

You might want to try int.TryParse(string, out int) in the KeyPress(object, KeyPressEventArgs) event to check for numeric values. For the other problem you could use regular expressions instead.

I used the TryParse that #fjdumont mentioned but in the validating event instead.
private void Number_Validating(object sender, CancelEventArgs e) {
int val;
TextBox tb = sender as TextBox;
if (!int.TryParse(tb.Text, out val)) {
MessageBox.Show(tb.Tag + " must be numeric.");
tb.Undo();
e.Cancel = true;
}
}
I attached this to two different text boxes with in my form initializing code.
public Form1() {
InitializeComponent();
textBox1.Validating+=new CancelEventHandler(Number_Validating);
textBox2.Validating+=new CancelEventHandler(Number_Validating);
}
I also added the tb.Undo() to back out invalid changes.

this way is right with me:
private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}

TRY THIS CODE
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("Please enter number only...");
e.Handled = true;
}
}
Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx

You can check the Ascii value by e.keychar on KeyPress event of TextBox.
By checking the AscII value you can check for number or character.
Similarly you can write logic to check the Email ID.

I think it will help you
<script type="text/javascript">
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 32 && (charCode < 48 || charCode > 57) && (charCode != 45) && (charCode != 43) && (charCode != 40) && (charCode != 41))
return false;
return true;
}

try
{
int temp=Convert.ToInt32(TextBox1.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}

Related

How to enable control key functionality in windows form application?

I am using the following textbox keypress() event to capture the keystrokes entered by user to restrict user to enter alphabet and numeric values.
private void textBoxName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) ||
e.KeyChar == (char)Keys.Space ||
e.KeyChar == (char)Keys.Back ||
e.KeyChar==(char)Keys.ControlKey );
}
Now the problem is by using the above mentioned code I am not able to use shortcut keys like Ctrl+C or Ctrl+v even if keys.ControlKey is handled in the the keypress event.
What i am doing wrong here?
Thanks in advance.
The Keypress event is not raised if the Control key is pressed without any other key. Is used as a key modifier only. In this case, e.KeyChar returns a modified value that char.IsLetter() considers false, the ! operator transforms it in true and assigns it to e.Handled, thus the keypress event is canceled.
to capture the keystrokes entered by user to restrict user to enter
alphabet and numeric values.
If, as you said, numbers are part of the required input, char.IsLetterOrDigit() should be used instead of char.IsLetter().
And punctuation? Is part of the input too?
These symbols are considered punctuation by char.IsPunctuation(): \"%&/()?*#.,:;_-'
Two methods to have the same result.
In both, char.IsControl(e.KeyChar) is used to check if Control is part of the Keycode and if it is, strip it by XOR(ing) it.
1) Filter using a simple regex. This one gives you more control on what to filter.
Regex _KeyFilter = new Regex(#"^[a-zA-Z0-9.,]");
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Return && e.KeyChar != (char)Keys.Space)
{
e.Handled = !_KeyFilter.IsMatch((char.IsControl(e.KeyChar)
? (char)(e.KeyChar ^ 64)
: e.KeyChar).ToString());
}
}
2) Filtert using char.IsLetterOrDigit() and char.IsPunctuation()
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Return && e.KeyChar != (char)Keys.Space)
{
char _keypress = char.IsControl(e.KeyChar) ? (char)(e.KeyChar ^ 64) : e.KeyChar;
e.Handled = !char.IsLetterOrDigit(_keypress) && !char.IsPunctuation(_keypress);
}
}

How to make keypress oemMinus and oemComma ( + digits) acceptable

I have a textbox in my application which I only want the user to be able to choose the "minus", "comma", "digits" and "back" from the keyboard. Can only make the user use digits and the back key, the rest doesn't work.
private void BoxMaxY_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back ||
!(e.KeyChar == (char)Keys.OemMinus || !(e.KeyChar == (char)Keys.Oemcomma))))
{
e.Handled = true;
}
}
Because your code says: handle if it's not minus or not comma, remove the "!" from those checks.

WinForms Textbox only allow numbers between 1 and 6

I want to restrict my WinForms Textbox so it only allows numbers between 1 and 6 to be entered. No letters, no other symbols or special characters, just those numbers.
How do I do that?
You could put this on the KeyPress event of the textbox,
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar)
{
//allowed keys 1-6 + backspace and delete + arrowkeys
case (char)Keys.Back:
case (char)Keys.Delete:
case (char)Keys.D0:
case (char)Keys.D1:
case (char)Keys.D2:
case (char)Keys.D3:
case (char)Keys.D4:
case (char)Keys.D5:
case (char)Keys.D6:
case (char)Keys.Left:
case (char)Keys.Up:
case (char)Keys.Down:
case (char)Keys.Right:
break;
default:
e.Handled = true;
break;
}
}
If the pressed key is (numpad) 1-6 , backspace , delete or arrowkeys allow them.
If it is a diffrent key don't place it and say it's handled. I tested this code on a quick project it allowed me to place using the numpad 1-6 don't know of the other numbers. If the others don't work you just have to add them as allowed and the arrow keys are not tested, but they are only needed to move left and right.
Have you tried SupressKeyPress?
if (e.KeyCode < Keys.D1 || e.KeyCode > Keys.D6 || e.Shift || e.Alt)
{
e.SuppressKeyPress = true;
}
if (e.KeyCode == Keys.Back)
{
e.SuppressKeyPress = false;
}
The 2nd If makes you able to press backspace if you want to change what you wrote.
The following regex should work
Regex rgx = new Regex(#"^[1-6]+$");
rgx.IsMatch("1a23"); //Returns False
rgx.IsMatch("1234"); //Returns True;
You should be able to use it with ASP.Net Validations and WinForms
https://msdn.microsoft.com/en-us/library/3y21t6y4(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx
Keep in mind that I'm suggesting a validation after the value is submitted which may not be what you're wanting. To me, the question is ambiguous here. Assuming you are using ASP.Net and you are wanting to restrict typing the values, the key press events solutions prior answers should work, but they will require at least a partial post back. If you are want this to be handle without a post back it will require a client side script.
This is an example of how to do it client side:
Restricting input to textbox: allowing only numbers and decimal point
Since the example is for any number you will have to restrict it to the digits 1 - 6.
Here you have a simple WebForm C# with code behind on submit that will validate regex for numbers between 0-6.
HTML
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">
<asp:TextBox runat="server" ID="tbForValidation"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="Validate" OnClick="btnSubmit_Click" />
</p>
</div>
Code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Regex regularExpression = new Regex(#"^[0-6]$");
if (regularExpression.IsMatch(tbForValidation.Text))
{
//Is matching 0-6
}
else
{
//Is not matching 0-6
}
}
I would also suggest that you run RegEx validation on client side before sending request to server. That will not create any unnecessary request to server for simple validation on textbox.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid number" ValidationExpression="^[0-6]$" ControlToValidate="tbForValidation"></asp:RegularExpressionValidator>
I would do something like this
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.D2 || e.KeyCode == Keys.D3 || e.KeyCode == Keys.D4 || e.KeyCode == Keys.D5 || e.KeyCode == Keys.D6)
{
e.Handled = true;
}
}
You could maybe allow use of control buttons as well e.g. Backspace
Add limit: 0 to 6 and use this:
private void txtField_KeyPress(object sender, KeyPressEventArgs e)
{
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;
}
Try this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int tester = 0;
try
{
if (textBox1.Text != null)
{
tester = Convert.ToInt32(textBox1.Text);
if (tester >= 30)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
textBox1.Select(textBox1.Text.Length, 0);
}
}
}
catch (Exception)
{
if (textBox1.Text != null)
{
try
{
if (textBox1.Text != null)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
textBox1.Select(textBox1.Text.Length, 0);
}
}
catch (Exception)
{
textBox1.Text = null;
}
}
}
}
Use regex #"^[1-6]$" to validate this type of input in textbox.
This WILL restrict you to 1 - 6.
I have no idea how you want to use it.
therefore, I am simply giving you code that will provide the restriction.
this is extremely archaic, more like plebeian.
First, I made a form:
Then I added the following code to the button:
int testValue;
// only numbers will drop into this block
if(int.TryParse(textBox1.Text, out testValue)){
// hard coded test for your desired values
if(testValue == 1 || testValue == 2 || testValue == 3 || testValue == 4 || testValue == 5 || testValue == 6){
// this is here just to give us proof of the return
textBox1.Text = "Yep, 1 - 6";
}
else{
// you can throw an exception here, popup a message, or populate as I did here.
// this is here just to give us proof of the return
textBox1.Text = "Nope, not 1 - 6";
}
}
// you can throw an exception here, popup a message, or populate as I did here.
else{
textBox1.Text = "Not a number";
}
If you enter any non number the text box reads "Not a number".
1 - 6 will read "Yep, 1 - 6".
any number < or > 1 - 6 will read " Nope, not 1 - 6".
Good luck!

C# When using a KeyPress event on a text box, why cant i enter a minus sign?

Im using VS2010, and I have a text box... I assign a KeyPress on the box, abd set the method like so:
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
I noticed that i am no longer able to enter any special keys such as the minus (-) and plus (+) sign into the textbox. Can someone please explain to me why i am no longer able to do this, and what i can do to fix this?
Ultimately I'm trying to only allow numeric keys to be entered, and i also want to allow the (-) minus sign, but if i cant get the minus sign in there, then i guess i wont be able to limit the text of the box
This should finish the job for you.
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
e.Handled = true;
}
Here is how it works. If the character typed is one that you want, simply return from the function and let the normal handler take care of it. All other characters are marked as handled and so processing on them stops. Since nothing is done with them they are essentially thrown away. You could put everything in one if statement but I left it this way for clarity
I changed your code a little and added logic that only accepts 1, 2 or +, which was one of your problem characters. Hope this helps you!
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
if (e.KeyChar == '1' || e.KeyChar == '2' || e.KeyChar == '+') textBox1.AppendText(e.KeyChar.ToString());
}
Actually, you should do like so:
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1' || e.KeyChar == '2' || e.KeyChar == '+')
e.Handled = false;
else
e.Handled = true;
}
Of course, you'll want to replace the individual tests by a method that will return whether or not the key is allowed.
Cheers
As it is now, your code won't allow anything to be entered. The e.Handled statement cancels the key stroke. The code below will allow any numeric character, and the minus sign. If you only want the minus sign in the first position in the textbox you will have to test the TextLength property before allowing the character.
private void MyButton_KeyPress(object sender, KeyPressEventArgs e
{
int i = 0;
if (!int.TryParse(e.KeyChar.ToString(), out i))
{
if (e.KeyChar.CompareTo('-')!=0)
{
e.Handled = true;
}
}
}

Restricting characters in a TextBox

I'm building a form in a C# WinRT app, and I'd like to restrict the characters in one of the TextBox components to numerals only. (This TextBox would be for a user to enter a year into.)
I've searched for a while, but haven't been able to figure this one out without setting up an event listener on the TextChanged event, and inspecting the text property on every key press. Is there a way to simply say that a user can only enter specific characters into a TextBox?
The simplest thing that could possibly work is to bind to the OnTextChanged event and modify the text according to your rules.
<TextBox x:Name="TheText" TextChanged="OnTextChanged" MaxLength="4"/>
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (TheText.Text.Length == 0) return;
var text = TheText.Text;
int result;
var isValid = int.TryParse(text, out result);
if (isValid) return;
TheText.Text = text.Remove(text.Length - 1);
TheText.SelectionStart = text.Length;
}
However, I'd shy away from this approach since the mantra of Metro is touch first UI and you can easy do it in a touch first manner with a FlipView control.
Try setting TextBox.InputScope property to InputScopeNameValue.Number, as mentioned in Guidelines and checklist for text input in MSDN.
Valid Year
DateTime newDate;
var validYear = DateTime.TryParseExact("2012", "yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out newDate); //valid
Invalid Year
var validYear = DateTime.TryParseExact("0000", "yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out newDate); //invalid
This seems to work for me:
private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if ((e.Key < VirtualKey.Number0) || (e.Key > VirtualKey.Number9))
{
// If it's not a numeric character, prevent the TextBox from handling the keystroke
e.Handled = true;
}
}
See the documentation for the VirtualKey enumeration for all the values.
Based on a posting at link, adding the tab to allow navigation.
private void decimalTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
bool isGoodData; // flag to make the flow clearer.
TextBox theTextBox = (TextBox)sender; // the sender is a textbox
if (e.Key>= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9) // allow digits
isGoodData = true;
else if (e.Key == Windows.System.VirtualKey.Tab)
isGoodData = true;
else if (e.Key >= Windows.System.VirtualKey.NumberPad0 && e.Key <= Windows.System.VirtualKey.NumberPad9) // allow digits
isGoodData = true;
else if (e.Key == Windows.System.VirtualKey.Decimal || (int)e.Key == 190) // character is a decimal point, 190 is the keyboard period code
// which is not in the VirtualKey enumeration
{
if (theTextBox.Text.Contains(".")) // search for a current point
isGoodData = false; // only 1 decimal point allowed
else
isGoodData = true; // this is the only one.
}
else if (e.Key == Windows.System.VirtualKey.Back) // allow backspace
isGoodData = true;
else
isGoodData = false; // everything else is bad
if (!isGoodData) // mark bad data as handled
e.Handled = true;
}
Use a MaskedTextBox control. For numerals only, just use the Mask property to specify the characters and the length, if any. e.g. if you want only five numbers to be entered, you set the mask property to "00000". Simple as that. Windows handles the restriction for you.

Categories

Resources