Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Mask = "*[L]";
maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
}
How can I set it to accept only letters, but however many the user wants? Thanks!
This would be easy if masked text boxes accepted regular expression, but unfortunately they don't.
One (albeit not very pretty) way you could do it is to use the optional letter ? mask and put in the same amount as the maximum length you'll allow in the text box, i.e
maskedTextBox1.Mask = "????????????????????????????????.......";
Alternatively you could use your own validation instead of a mask and use a regular expression like so
void textbox1_Validating(object sender, CancelEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, #"^[a-zA-Z]+$"))
{
MessageBox.Show("Please enter letters only");
}
}
Or yet another way would be to ignore any key presses other than those from letters by handling the KeyPress event, which in my opinion would be the best way to go.
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), #"^[a-zA-Z]+$"))
e.Handled = true;
}
If you want only letters to be entered you can use this in keyPress event
if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)) //The latter is for enabling control keys like CTRL and backspace
{
e.Handled = true;
}
Related
I have several text boxes and would like to format them all the same way with these rules:
// limits to number, control keys, and decimal
// goes to the next text box when enter
private void tb_text1_KeyPress_1(object sender, KeyPressEventArgs e)
{
string newString = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
tb_text1.MaxLength = 6;
e.Handled = (!char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) && e.KeyChar != '.');
if (e.KeyChar == (char)(Keys.Enter))
{
this.GetNextControl(ActiveControl, true).Focus();
}
}
// removes restricted chars
private void tb_text1_Enter(object sender, EventArgs e)
{
tb_text1.Text = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
}
// applies format at exit
private void tb_text1_Leave(object sender, EventArgs e)
{
tb_text1.Text = string.Format("{0,-6} [Ohm]", decimal.Parse(tb_text1.Text));
}
What is the best way? create a new text box class based on the text box?
Thanks.
Replace in methods your "tb_text1" variable to the "((TextBox)sender)", and now You can use Your code for any textbox.
It is very easy to do it with javascript . Please try that. I have done it i'm not able to find piece of that code right now . It is worth the effort because it will be very fast and will be running on client side.
I have a textbox and want user can not enter space in first textbox.the user can enter space in any where textbox apart of Beginning textbox.my computer = allow my computer = not allow (space in begining) , space maybe one or two or more.
If you really insist on doing this using one of the Events I would suggest you do it in the Text_Changed Event I have set you a simple way to do it..
private void txtaddgroup_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
if (textBox.Text.StartsWith(" "))
{
MessageBox.Show("Can not have spaces in the First Position");
}
}
Implement a keypress event where you get rid of any spaces, read more here.
Add this bit of code to your KeyDown event handler to stop the space key ever being registered:
//Check to see if the first character is a space
if (UsernameTextBox.SelectionStart == 0) //This is the first character
{
//Now check to see if the key pressed is a space
if (e.KeyValue == 32)
{
//Stop the key registering
e.Handled = true;
e.SuppressKeyPress = true;
}
}
32 if the Key Code for the space character.
You should call this function with parameter as 'e' on KeyPress event:
Here 32 is the ASCII value of space
void SpaceValidation(KeyPressEventArgs e)
{
if (e.KeyChar == 32 && ActiveControl.Text.Length == 0)
e.Handled = true;
}
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
SpaceValidation(e);
}
I m Developing A windows Application i m easily handle to enter the only numbers in Text box using key press event. but i still able to paste alpha bates in text boxes how can i restrict to paste alpha bates in text box
us the use the TextChanged event.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var rgx = new Regex(#"\D");
textBox1.Text = rgx.Replace(textBox1.Text, "");
}
Use KeyPress event,
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
You don't explicitly state what UI technology you're using, but if it's WinForms you could try using a MaskedTextBox with the appropriate mask property setting.
MSDN MaskedTextBox Mask Property
So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.
Why you dont put the money sign "$" out side of the textBox (create a label just infrontof textBox), then you will not have to worry about this character, but only about numbers. And it looks better (in my opinion).
Then you can use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (Char)Keys.Back) //allow backspace (to delete)
{
e.Handled = !char.IsNumber(e.KeyChar);
}
}
All validation should be performed manually on KeyPress event.
Here described validation for numeric values values. You will need to check the '$' sign and decimals additionally.
I think you are using WinForms and not WPF. If that is the case then you could use System.Windows.Forms.ErrorProvider (you can drag-drop one from toolbox to your form) along with regular expressions to do the validation.
WARNING: The regex pattern string below may not do exactly you want but hopefully conveys the idea.
Some match examples... "$4,000.00", "-$4000.00", "-$400.00"
private void textBox1_Validating(object sender, CancelEventArgs e)
{
string error = null;
string pattern = #"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$";
if (!Regex.IsMatch(textBox1.Text, pattern))
{
error = "Please enter a US currency value.";
e.Cancel = true;
}
errorProvider1.SetError((Control)sender, error);
}
There are a number of articles on numeric textboxes
Numeric TextBox
http://www.daniweb.com/software-development/csharp/threads/95153
http://www.codeproject.com/KB/vb/NumericTextBox.aspx
I use this one in my projects
http://www.codeproject.com/KB/edit/ValidatingTextBoxControls.aspx
//tb - is the name of text box
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
char[] inputChar = e.Text.ToCharArray();
if (char.IsNumber(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
// another method.
if (char.IsDigit(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Have you tried Ajax Controls?
http://www.aspsnippets.com/Articles/ASPNet-AJAX-FilteredTextBoxExtender-Control-Example.aspx
Simples. :)
How can only valid characters be allowed in a Windows file system in a TextBox that can only appear as uppercase in Windows Forms?
Is there an easy way for this?
About the set of characters allowed in a Windows file system (Char.IsLetterOrDigit is not enough)
How do I make the typed characters uppercase?
Create a Textbox key press handler and Use Path.GetInvalidPathChars(), Path.GetInvalidFileNameChars() to check for a valid char and return the uppercase version if the char is valid.
textBox1.CharacterCasing = CharacterCasing.Upper;
...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Path.GetInvalidFileNameChars().Contains(e.KeyChar) ||
Path.GetInvalidPathChars().Contains(e.KeyChar))
{
e.Handled = true;
}
}
[Of course, it would be more reusable to create a method rather than placing this code directly in the handler.]
UPDATED to reflect comments.
Here's my solution. It works perfectly for windows file names convention. Cheers.
// Prevent user from wrong input - \/:*?"<>|
private void textBoxMP3Name_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), #"[^?:\\/:*?\""<>|]"))
{
e.Handled = true;
}
}
A Better way for me was to use the TextChanged Event ala:
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
...
private void textBox1_TextChanged(object sender, EventArgs e)
{
char[] invalidChars = Path.GetInvalidFileNameChars();
textBox1.Text = string.Join("", textBox1.Text.Split(invalidChars));
textBox1.SelectionStart = textBox1.Text.Length + 1;
}
because ... you need backspace and user simply love copy & paste ...