Hi guys help please! how will i make my textbox to accept letters and numbers only? thanks in advance!
Printable View
Hi guys help please! how will i make my textbox to accept letters and numbers only? thanks in advance!
Try this:
csharp Code:
public class NumericTextBox : TextBox { public NumericTextBox() { } protected virtual int[] AlwaysValid { get { return new int[] { 1, 3, 8, 13, 22, 24 }; } //Allow paste, copy, backspace etc... } public override string Text { get { return base.Text; } set { if (value.ToCharArray().Where((char c) => !char.IsLetterOrDigit(c)).Count() == 0) base.Text = value; } } protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x302: string pasteText = Clipboard.GetText(); if (pasteText.ToCharArray().Where((char c) => !char.IsLetterOrDigit(c)).Count() > 0) { return; //Invalid paste string } break; case 0x102: case 0x106: case 0x286: char keyChar = (char)m.WParam; if (!char.IsLetterOrDigit(keyChar) && (Array.IndexOf(this.AlwaysValid, m.WParam.ToInt32()) == -1)) { return; //Invalid key char press } break; } base.WndProc(ref m); } }
Hey,
The above will give you a Numeric Textbox only, however, I think what you are looking for is an alpha numeric textbox, in which case you can simply add the following to the KeyPress Event Handler for the TextBox:
Hope that helps!!Code:private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Allows only Alpha-Numeric’s
if (!(Char.IsLetter(e.KeyChar) || Char.IsDigit(e.KeyChar) || Char.IsControl (e.KeyChar)))
e.Handled = true;
}
Gary
No it's an alpha numeric text box. If you look at the code you will see 'char.IsLetterOrDigit'. The name is however misleading. Also your code does not account for paste attempts, or for the designer changing the text/lines property in design mode.
Hey,
You are correct.
What I have presented is simply a basic modification to the standard textbox, which will only validate key presses directly into the textbox while in run mode.
The OP didn't specifically state which situations they wanted to account for though.
Gary
True, but I think it's good practice to account for all situations.Quote:
Originally Posted by gep13
Hey,
You are correct, I think I was just being lazy :)
One other thing that you might want to think about is the use of the MaskedTextBox:
http://msdn.microsoft.com/en-us/libr...edtextbox.aspx
Depending on what exactly you are trying to achieve, you may be able to do it with the Mask Property.
Gary
Thanks guys! may be i'll use what forumaccount suggested but thanks gep!
Hey,
Not a problem with that.
If your question has been answered though, remember to mark the thread as resolved.
Gary