How do I limit textbox from accepting letter A,B,C,D only? I've tried this code, but it still accepts letters aside from letters A,B,C,D.
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
I agree with the comment that if all you want is a single character that actually using a combo box may be more appropriate, but if you're planning on allowing the user to enter a series of the limited characters then it may be worth having a look at an article that I wrote a few years ago about how to restrict the characters that are allowed in the text box, which is available at "Restrict characters entered into textbox".
Further to DanDan78's comment below the important code is;
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
On the KeyPress event of your TextBox, you can just use this simple code to achieve your aim:
if (e.KeyChar < 'A' || e.KeyChar > 'D')
e.Handled = true;
If you wish to accept lower and upper case A-D:
if ((e.KeyChar < 'A' || e.KeyChar > 'D') && (e.KeyChar <'a' || e.KeyChar > 'd'))
e.Handled = true;
If you also wish to allow 'special' characters like backspace, delete, etc., you need to also allow characters below ASCII code 32:
if ((e.KeyChar < 'A' || e.KeyChar > 'D') && (e.KeyChar <'a' || e.KeyChar > 'd') && e.KeyChar > 32)
e.Handled = true;
Following a further user comment, in order to allow A-D, a-d and backspace only, the following should suffice:
if ((e.KeyChar < 'A' || e.KeyChar > 'D') && (e.KeyChar <'a' || e.KeyChar > 'd') && e.KeyChar != 8)
e.Handled = true;
Attach a KeyPressEventHandler to the text box:
textBox.KeyPress += new KeyPressEventHandler(keyPressed);
Then create an event to handle these letters:
private void keyPressed(Object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'A' || e.KeyChar == 'B' || e.KeyChar == 'C' || e.KeyChar == 'D')
{
e.Handled = true;
}
}
This will stop the text box accepting these letters
Related
hello i wanna understand this code .. i just take it copy past to my work space
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;
}
}
Simply speaking a key event is sent to a chain of event handlers. Whenever someone says "I've handled it", the chain stops. So, when the key press is outside the range of numbers and not backspace or decimal point, this code sets e.Handled to true and the chain stops. That means event handling stops and the key is not shown in the textbox.
I wish to validate this TextBox against negative values and characters (must be integer without decimal)
It works well for . but I am not able to understand why it accepts negative value and characters?
My code is :
private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && (e.KeyChar == '.') && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back))
e.Handled = true;
}
You need to replace the first && operator with || and also move it to the end of your if statement then it should works as you want. Like this:
private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back) || (e.KeyChar == '.'))
e.Handled = true;
}
I want delete one character minus - that the user press in a textbox. I validate that the user has not pressed the minus key twice with event key_press:
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one minus -
if (e.KeyChar == '-' && ((sender as TextBox).Text.IndexOf('-') > -1))
{
e.Handled = true;
}
the problem is when the user presses the minus sign key in middle or end of the string. For example:
1000.-00 <--- Invalid
2000.00- <--- Invalid
-1000.00 <--- valid
How can I ensure the minus sign is beginning the contents of the text box?
if (e.KeyChar == '-' && ((sender as TextBox).Text.Length > 1))
This allows only one dash at the beginning. Maybe you need to trim the Text first...
use it like this
declare a variable at class level like this int minusCount=0;
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one minus -
//put condition if it is zero than only allow one minus sign
if (e.KeyChar == '-' && ((sender as TextBox).Text.IndexOf('-') > -1) && minusCount==0)
{
e.Handled = true;
//over here increment that variable
minusCount = minusCount+1;
//for handling it in middle other than zero position
if(textbox.Text.IndexOf("-")>1)
{
textbox.Text=textbox.Text.Replace("-","");
}
}
The problem with your second if is that at the time when you do the check the sender (i.e. the TextBox) does not have the minus yet. You should construct the text with the minus first, then validate it to make a decision:
if (e.KeyChar == '-') {
var tb = sender as TextBox;
// Obtain the text after the modification
var modifiedText = tb.Text.Insert(tb.SelectionStart, "-");
// There will be at least one '-' in the text box - the one you just inserted.
// Its position must be 0, otherwise the string is invalid:
e.Handled = modifiedText.LastIndexOf("-") != 0;
}
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'm trying to set a hex mask for a textbox. So that only valid hex numbers can be entered. (And ',' and 'ENTER')
It almost works. So far it will only allow small letters from a-f and numbers 0-9, but I can still enter capital letters GHIJKLM. (At first, when program is started it seems to accept one char ex k, but after it has excepted k once it wont be shown after that, until next time you start the program. That's weird.)
Here is a part of code:
private void EnterKey(Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// if keychar == 13 is the same as check for if <ENTER> was pressed
if (e.KeyChar == (char)13)
{
// is <ENTER> pressed, send button_click
button1_Click(sender, e);
}
{
// this will only allow valid hex values [0-9][a-f][A-F] to be entered. See ASCII table
char c = e.KeyChar;
if (c != '\b' && !((c <= 0x66 && c >= 61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
{
e.Handled = true;
}
}
}
This is how I bind the event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyDown);
}
Could anyone of you wise guys, see what I'm doing wrong?
It's my first small program, so go easy on me :o)
This:
c <= 0x66 && c >= 61
Should be:
c <= 0x66 && c >= 0x61 //hex literal
Note that you're wasting valuable time by looking up hex codes, you can easily compare characters:
if ((c >= 'a') && (c <= 'f'))
As for the first character: you shouldn't bind the KeyPress at the TextChanged event - it is too late! Here's the sequence of events:
Form Loads
...
User click on a key.
TextChanged triggered, changing the text and binding the event.
User click on a key.
KeyPress triggered.
What you want to do is to bind the event right from the start. The best place is the Form_Load event.
You can also use the Properties window to bind the event at design time
If you had not used magic numbers, you would never have run into this problem. Rewrite your if like this:
if (!(c == '\b' || ('0' <= c && c <= '9') || ('A' <= c && c <= 'F') // et cetera
Use a regular expression:
using System.Text.RegularExpressions;
...
if (!(Regex.IsMatch(e.KeyChar.ToString(), "^[0-9a-fA-F]+$"))
e.Handled = true;
What type of program is this an ASP.NET website or some type of winforms/wpf thick client? The reason I ask is that you may be testing on stale code. Otherwise on change can be to just flip the checking logic to be more aligned with what you want. Ensuring that the entered character is one element in the allowed set. A refactoring is below.
e.Handled = (c >= 0x61 && c <=0x66) || (c >=0x41 && c<= 0x46) || (c >= 0x30 && c <= 0x39);
As an alternative approach if you just want to validate the whole textbox at one time instead of after each key press you can just parse the value to see if it is a number. The following code fragment will generate parse the value 11486525 from AF453d. If the number is not a valid hex value then the result of isHex will be false;
int i;
string s = "AF453d";
bool isHex;
isHex = int.TryParse(s, System.Globalization.NumberStyles.AllowHexSpecifier, null, out i);
Console.WriteLine(isHex);
Console.WriteLine(i);
Why complicate it?
private void EnterKey(Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
char c = e.KeyChar;
e.Handled = !System.Uri.IsHexDigit(e.KeyChar) && c != 0x2C;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
/* less than 0 or greater than 9, and
* less than a or greater than f, and
* less than A or greater than F, and
* not backspace, and
* not delete or decimal (which is the same key as delete). */
if (
((e.KeyChar < 48) || (e.KeyChar > 57)) &&
((e.KeyChar < 65) || (e.KeyChar > 70)) &&
((e.KeyChar < 97) || (e.KeyChar > 102)) &&
(e.KeyChar != (char)Keys.Back) &&
((e.KeyChar != (char)Keys.Delete) || (e.KeyChar == '.'))
) e.Handled = true;
}
Based on the answer by Kobi for WPF
private void EnterKey(Object sender, KeyEventArgs e)
{
Key c = e.Key;
if (!((c >= Key.A) && (c <= Key.F)))
{
if (!((c >= Key.D0) && (c <= Key.D9)))
{
if (!((c >= Key.NumPad0) && (c <= Key.NumPad9)))
{
e.Handled = true;
LogText("Handled");
}
}
}
}
Captures letters, numbers and keypad numbers.