I am trying to disable all keystrokes entered into a text box except the following:
0 1 2 3 4 5 6 7 8 9 . (so all keys except the numbers and the '.' should be disabled)
Right now I have the following code but it only checks to see if a letter was entered as the first value (not to mention its really sloppy):
private void yDisplacementTextBox_TextChanged(object sender, EventArgs e)
{
if (yDisplacementTextBox.Text.ToUpper() == "A" || yDisplacementTextBox.Text.ToUpper() == "B" || yDisplacementTextBox.Text.ToUpper() == "C" ||
yDisplacementTextBox.Text.ToUpper() == "D" || yDisplacementTextBox.Text.ToUpper() == "E" || yDisplacementTextBox.Text.ToUpper() == "F" ||
yDisplacementTextBox.Text.ToUpper() == "G" || yDisplacementTextBox.Text.ToUpper() == "H" || yDisplacementTextBox.Text.ToUpper() == "I" ||
yDisplacementTextBox.Text.ToUpper() == "J" || yDisplacementTextBox.Text.ToUpper() == "K" || yDisplacementTextBox.Text.ToUpper() == "L" ||
yDisplacementTextBox.Text.ToUpper() == "M" || yDisplacementTextBox.Text.ToUpper() == "N" || yDisplacementTextBox.Text.ToUpper() == "O" ||
yDisplacementTextBox.Text.ToUpper() == "P" || yDisplacementTextBox.Text.ToUpper() == "Q" || yDisplacementTextBox.Text.ToUpper() == "R" ||
yDisplacementTextBox.Text.ToUpper() == "S" || yDisplacementTextBox.Text.ToUpper() == "T" || yDisplacementTextBox.Text.ToUpper() == "U" ||
yDisplacementTextBox.Text.ToUpper() == "V" || yDisplacementTextBox.Text.ToUpper() == "W" || yDisplacementTextBox.Text.ToUpper() == "X" ||
yDisplacementTextBox.Text.ToUpper() == "Y" || yDisplacementTextBox.Text.ToUpper() == "Z")
{
MessageBox.Show("Please enter a numeric value for the Y Displacement.", "Y Displacement: Numbers Only Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Is there anyway to have it so when pressed, all of the keys on the keyboard (except the numbers and the period button) do not register (or disables) the actual value of the key and inputs nothing?
Use textBox1.KeyPress += textBox1_KeyPress
This code only allowing numbers and . and the backspace.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
//Edit: Alternative
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
}
There are two ways you could try to approach this:
Wait for the user to finish entering the data, then use double.TryParse() to make sure it's a valid number.
Use the KeyPress event of the TextBox to validate the data as each key is pressed.
Take a look here: Simple Numeric TextBox
EDIT: As other answers explains what to do dealing with OnKeyPress/OnKeyDown events, this article demonstrates how to deal with other scenarios, as pasting text, so I'll keep this answer.
You should hook into the KeyDown and KeyPress event to prevent the input of unwanted characters. There is a sample on MSDN
Many third party control libraries also have this kind of functionality built in if you ever find yourself using one of them.
It is better practice to allow typing anything but give notification through an error provider about the failing validation (Validating event and double.TryParse()).
But if you insist, be sure to replace the '.' with the decimal separator of the system. If you are not assuming all values to be English you can easily get into a cannot-enter-a-decimal-value problem.
For instance, I am in Croatia and here we have to type a comma (,). In some islamic country I fail to remember the decimal separator is a hash (#).
So beware of localization issues.
The below code will suppress all but number, the backspace, and the decimal. It also only allows a single decimal for numeric entry.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
return;
}
if(e.KeyChar == '.' && textBox1.Text.Contains('.'))
{
e.Handled = true;
}
}
This also can be used
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.'){
e.Handled = true;}
Shortest fix to make text/cmb box read-only, attach following to respective keypress event :
private void cmbDisable_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = (char)(0);
}
Related
I Tried Some Codes But Didnt Work
For Example
I Found This And It Didnt Work:
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;
}
You have a very simple, yet understandable error there.
The Handled property of KeyPressEventArgs should be set to true to keep the operating system from further processing the key.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keypresseventargs?view=netframework-4.8
In other words, set this to true when you want to PREVENT the key.
Therefore, change your code like this to ALLOW further processing when the pressed key fits the conditions.
Please also see how the boolean variables are introduced to make the code readable.
The code below allows
A ( - ) character if it is the first char in the text box
A ( . ) character if it is not the first char and if there are no other dots
Any control characters
And any digits.
Good luck.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
bool isControl = char.IsControl(e.KeyChar);
bool isDigit = char.IsDigit(e.KeyChar);
bool isDot = e.KeyChar == '.';
bool alreadyHasADot = (sender as TextBox).Text.IndexOf('.') != -1;
bool isHyphen = e.KeyChar == '-';
bool isFirstChar = (sender as TextBox).Text.Length == 0;
bool isAllowed =
isControl ||
isDigit ||
(isDot && !isFirstChar && !alreadyHasADot) ||
(isHyphen && isFirstChar);
if (!isAllowed)
{
e.Handled = true;
}
}
Sorry if this is a really basic question but I'm new to C# and it's my first windows form app.
In the code below my TextBox only accepts a decimal point ",", a minus sign "-", digits, and it also accepts the input of the delete and backspace keys (correct me if I'm wrong). So I can input and delete numbers like:
-12.31
-.31
The problem is I can also input something like:
12-
Is there a way to only input "-" if its the first character of the string? I tried google and I tried to come up with something but nothing seems to work.
And thank you for your time.
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && (e.KeyChar != ',') && (e.KeyChar != '-') && (e.KeyChar != (char)8))
{
e.Handled = true;
}
if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
{
e.Handled = true;
}
if ((e.KeyChar == '-') && ((sender as TextBox).Text.IndexOf('-') > -1))
{
e.Handled = true;
}
}
You can check where the cursor is by using SelectionStart:
var textBox = (TextBox)sender;
if (e.KeyChar == '-' && (textBox.SelectionStart !=0 || textBox.Text.Contains("-")))
{
e.Handled = true;
}
hey I have a problem with my wpf webbrowser. I dont want that you can press shortcuts like "CRTL + N" for a new tab for example. I already found out how to do it, but if I want to handle more shortcuts it will only prevent the last one. I know that this will be very simple but I dont know how to fix it at the moment. Here is my code:
e.Handled = e.Key == Key.N && e.KeyboardDevice.Modifiers == ModifierKeys.Control;
e.Handled = e.Key == Key.O && e.KeyboardDevice.Modifiers == ModifierKeys.Control;
e.Handled = e.Key == Key.OemMinus && e.KeyboardDevice.Modifiers == ModifierKeys.Control;
e.Handled = e.Key == Key.OemPlus && e.KeyboardDevice.Modifiers == ModifierKeys.Control;
e.Handled = e.Key == Key.Subtract && e.KeyboardDevice.Modifiers == ModifierKeys.Control;
e.Handled = e.Key == Key.Add && e.KeyboardDevice.Modifiers == ModifierKeys.Control;
You need to OR together your conditions.
e.Handled = ((e.Key == Key.N) && (e.KeyboardDevice.Modifiers == ModifierKeys.Control)) ||
((e.Key == Key.O) && (e.KeyboardDevice.Modifiers == ModifierKeys.Control)) ||
((e.Key == Key.OemMinus) && (e.KeyboardDevice.Modifiers == ModifierKeys.Control)) ||
((e.Key == Key.OemPlus) && (e.KeyboardDevice.Modifiers == ModifierKeys.Control)) ||
((e.Key == Key.Subtract) && (e.KeyboardDevice.Modifiers == ModifierKeys.Control)) ||
((e.Key == Key.Add) && (e.KeyboardDevice.Modifiers == ModifierKeys.Control));
As Modifier CTRL appears to be common, this can be separated out from the keys & the simplified code would be something like
e.Handled = (e.KeyboardDevice.Modifiers == ModifierKeys.Control) &&
((e.Key == Key.N) || (e.Key == Key.O) || (e.Key == Key.OemMinus) || ...... )
Note that I have added brackets that some people will say are unnecessary, but I prefer them for readability.
Note: This is not about EXCEPTIONS!
I'm trying to make a textbox accept everything but Symbols and Punctations... but I need to allow "," and "." . I'm using:
if (char.IsPunctuation(e.KeyChar) == true)
{
e.Handled = true;
}
if (char.IsSymbol(e.KeyChar) == true)
{
e.Handled = true;
}
Is there anyway to make an exception for those two Characters ( , and . ) ?
Check for these characters first:
if(e.KeyChar != ',' && e.KeyChar != '.')
{
if (char.IsPunctuation(e.KeyChar))
{
e.Handled = true;
}
if (char.IsSymbol(e.KeyChar))
{
e.Handled = true;
}
}
Note on style: There is no need to compare a boolean to true in order for the branch to be taken.
Try this:
if (char.IsPunctuation(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.')
{
e.Handled = true;
}
if (char.IsSymbol(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.')
{
e.Handled = true;
}
Or you could simply check it before all of that:
if( e.KeyChar != ',' && e.KeyChar != '.')
{
if (char.IsPunctuation(e.KeyChar) )
{
e.Handled = true;
}
if (char.IsSymbol(e.KeyChar) )
{
e.Handled = true;
}
}
What it does is checks if the character is punctuation/symbol and ALSO the character is NOT ',' or '.'. Therefor the if statement will not run if the character is a comma or period.
I've a textbox with an event that should do things when some text is entered. It's easy to check if it is alphanumeric as stated here Can I determine if a KeyEventArg is an letter or number? :
if ( ( ( e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z ) ||
( e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9 ) ||
( e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9 ) )
The problem with this approach is that I should also check manually for -?!¿[]() with Key.OemMinus, Key.OemQuestion, etc.
Is there some way to check if it's a text keystroke or I should check manually (which is not very elegant in my opinion)?
As no other option is suggested I used the following code to allow nearly all text keystrokes. Unfortunatelly, this is keyboard dependant so it's not very elegant. Hopefully is not a critical aspect in the application, it's only a matter of usability.
bool isText = (e.Key >= Key.A && e.Key <= Key.Z) || (e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
|| e.Key == Key.OemQuestion || e.Key == Key.OemQuotes || e.Key == Key.OemPlus || e.Key == Key.OemOpenBrackets || e.Key == Key.OemCloseBrackets || e.Key == Key.OemMinus
|| e.Key == Key.DeadCharProcessed || e.Key == Key.Oem1 || e.Key == Key.Oem7 || e.Key == Key.OemPeriod || e.Key == Key.OemComma || e.Key == Key.OemMinus
|| e.Key == Key.Add || e.Key == Key.Divide || e.Key == Key.Multiply || e.Key == Key.Subtract || e.Key == Key.Oem102 || e.Key == Key.Decimal;
this code allow just numbers and '.':
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
e.KeyChar != (char)(Keys.Delete) &&
e.KeyChar != (char)(Keys.Back))
{
e.Handled = true;
}
}