WinForms Textbox only allow numbers between 1 and 6 - c#

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!

Related

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.

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.

C# Numeric Only TextBox Control [duplicate]

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

KeyDown event - how to easily know if the key pressed is numeric?

I am currently handling the KeyDown event of a DataGridView control.
One of the columns is filled by calculated values and I want the user to be able to override the cell value if they want.
When the user presses a numeric key, the cell goes into EditMode and allows the user to override the value. If the key is not numeric, nothing happens...
That is working pretty well... the problem is that I find the code for it ugly...
I can't seem to find a neat way to handle all the numeric keys in a single condition, so I've made a switch case construct to deal with all the possible numeric keys, like this:
switch (e.KeyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.Decimal:
case Keys.NumPad0:
case Keys.NumPad1:
case Keys.NumPad2:
case Keys.NumPad3:
case Keys.NumPad4:
case Keys.NumPad5:
case Keys.NumPad6:
case Keys.NumPad7:
case Keys.NumPad8:
case Keys.NumPad9:
[code to make the cell go to editMode, etc...]
Sure, it works, but there has to be a better and shorter way, right?
All I could find using Google is converting e.KeyCode to a char, but when using numeric keys, it goes gives letters even for the numeric values...
Thanks.
Try
if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
e.KeyCode == Keys.Decimal)
{
// Edit mode
}
If you use the KeyPress event, the event signature has a KeyPressEventArgs with a KeyChar member that gives you the character for the numberpad keys. You can do a TryParse on that to figure out if its a number or not.
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
int i;
if (int.TryParse(e.KeyChar.ToString(), out i))
{
MessageBox.Show("Number");
}
}
Sorcerer86pt's solution was the simplest, however, when a user presses a control key, like backspace, then it breaks. To solve that problem, you can use the following snippet:
void KeyPress(object sender, KeyPressEventArgs e)
{
if(!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
//The char is not a number or a control key
//Handle the event so the key press is accepted
e.Handled = true;
//Get out of there - make it safe to add stuff after the if statement
return;
}
//e.Handled remains false so the keypress is not accepted
}
If you're using WPF, you might find that a TextBox doesn't have a KeyPressed event. To fix this, I used the following code.
void ValidateKeyPress(object sender, KeyEventArgs e)
{
char keyPressed = WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key);
if (!Char.IsNumber(keyPressed) && !Char.IsControl(keyPressed))
{
//As above
e.Handled = true;
return;
}
}
You may notice the weird function call WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key) this is one of the useful functions I've collected.
You can find it here.
Why use keycodes, when you can use this:
void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar))
{
//do something
}
else
{
//do something else
}
}
It's cleaner and even if microsoft decides to change all enums vlue, it still would work
On the msdn help page they use this code in their example:
// 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)
A bit more condensed version:
private void KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !Char.IsDigit(e.KeyChar); // only allow a user to enter numbers
}
Just get the last char from the Key that will be number if a number was pressed.
This method works with KeyDown events not needing any other conditions.
Just call this static method and pass in the Key to check
public static bool IsNumber(Keys key)
{
string num = key.ToString().Substring(key.ToString().Length - 1);
Int64 i64;
if (Int64.TryParse(num, out i64))
{
return true;
}
return false;
}
void dataGridView1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Used this to find they key values.
//label1.Text += e.KeyValue;
// Check if key is numeric value.
if((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyValue >= 97 && e.KeyValue <= 105))
System.Console.WriteLine("Pressed key is numeric");
}

Categories

Resources