I have prevented numbers from being typed in text box using key down event. But when using Ctrl+V or pasting content through mouse, the numbers are being entered in the text box. How to prevent this? I have to allow all text to be pasted/typed except numbers.
On quite simple approach would be to check the text using the TextChanged event. If the text is valid, store a copy of it in a string variable. If it is not valid, show a message and then restore the text from the variable:
string _latestValidText = string.Empty;
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox target = sender as TextBox;
if (ContainsNumber(target.Text))
{
// display alert and reset text
MessageBox.Show("The text may not contain any numbers.");
target.Text = _latestValidText;
}
else
{
_latestValidText = target.Text;
}
}
private static bool ContainsNumber(string input)
{
return Regex.IsMatch(input, #"\d+");
}
This will handle any occurrence of numbers in the text, regardless of where or how many times they may appear.
use the TextBox.TextChanged event. Then use the same code as you have in the KeyDown event. In fact, you no longer need the keydown event
You can use the JavaScript change event (onchange) instead of the keydown event. It'll check only when the user leaves the textbox though.
Related
I am working on a c# windows forms application and I have a text box which accepts a maximum of four character for which I am trying to raise am event when fourth character.
I tried to include it in KeyPress event but to raise the event I had to press a key after all the four characters are entered
private void txtFourC_KeyPress(object sender, KeyPressEventArgs e)
{
if ( txtFourC.TextLength == 4)
{
//code here
}
}
Is there a better way to do this may be other than Key_Press
To limit the maximum number of characters that users can type or paste into the TextBox, it's enough to set MaxLength property.
If you don't want to limit the user, but you want to be notified when the user entered more than 4 characters, handle TextChanged event and check for TextLength property to know length of text in the control.
Or use the event to f.e. jump to the next field after the 4th digit is typed.
So use the TextChanged event and check for TextLength property to know length of text in the control and activate the next field.
If the purpose is to restrict input to maximum 4 characters then its best to set MaxLength property. txtFourC.MaxLength=4
However, if you want to show message when 4th character is typed in then you may use KeyUp event instead KeyPress.
private void txtFourC_KeyUp(object sender, KeyEventArgs e)
{
if(txtFourC.Text.Length ==4)
{
MessageBox.Show("Reached max length");
}
}
private void txtFourC_TextChanged(object sender, KeyEventArgs e)
{
if(txtFourC.Text.Length == 4)
{
//do your control here.
}
}
I have a textbox in my winform in which after puting a validation using regex on keypress event, the default functionalities like copy paste etc of the textbox is not working.
How can i handle this?
Regex used code
private void textbox_keypress(object sender,keypresseventargs e)
{
var regex= new regex(#"^[0-9,]*$");
if(!regex.ismatch(e.keychar.tostring()))
{
e.handled=true;
}
}
after removing the keypress event handler everything is working fine but i have to restrict user to enter comma separated number value and also copy paste delete backspace in that textbox.
The Ctrl-Commands don't work because you abort their entries. To avoid this you must either
check if the Ctrl-Key has been pressed. The KeyPress event doesn't tell you that. This example from MSDN shows you how to do it: You script the KeyDown event to set (or clear) a flag variable, which you can then test in the KeyPress. No, not exactly elegant imho, but that's how MS tells you to do it.. (Note that I have added the Backspace code \b, as it isn't covered by the Ctrl-check..)
bool ctrlPressed = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
ctrlPressed = (Control.ModifierKeys == Keys.Control);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!ctrlPressed)
{
var regex= new Regex(#"^[0-9,\b]*$");
if (!regex.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}
}
Or, if you want better control over which Ctrl-Keys are allowed, skip the whole flags-affair and instead simply include them one by one in the allowed keys-brackets like this for ^C, ^X, ^A, ^V ^Z etc..:
var regex= new Regex(#"^[0-9,\b\cC\cX\cA\cV\cZ]*$");
Here is the description from MSDN:
\cX Matches an ASCII control character, where X is the letter of the
control character. For example, \cC is CTRL-C.
On a side note: The old fashioned copy&paste commands of Ctl-Ins and Shift-Ins work as normal even in your original code.
I am using the following code to extract the last character( the character just typed) using the following code
private string GetTypedChar()
{
string currentChar = "";
int i = rtfText.SelectionStart;
if (i > 0)
{
currentChar = rtfText.Text.Substring(i-1, 1);
MessageBox.Show(i+":"+currentChar);
}
return currentChar;
}
But this is giving me wrong results. If the word entered is "RS" the after pressing R the message box shows 1: (blank) then on typing S message box shows 2:R
How to achieve this?
to get the last entered character. You can handle the keyup event
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
char last = (char)e.KeyValue;
}
you can get the last character of your rich text box
string lastCharacter = rtfText.Text.SubString(rtfText.Text.Length - 1,1);
or
char last = rtfText.Text[rtfText.Text.Length - 1];
or
The important question is when you execute that code. Sounds like you subscribe to the 'KeyDown' event. By the time this event is raised, the key stroke has not yet been processed by the form --> So you don't see the change. You could use the KeyUp event. When this gets fired, your control has a changed context.
This will, however, not help you, if the new character is not the last one. The user could change the courser position and type a character. Then the new character is somewhere in the middle of the text. This can be solved by actually checking which key has been pressed. This information is in the KeyEventArgs parameter.
You could just eliminate GetTypedChar() altogether and subscribe to the KeyPress event.
Note that this won't give you the position of the character though, if you need that information.
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(string.Format("Last char typed: {0}", e.KeyChar));
}
I am using c# winform.
I have 2dimensional array of text boxes I want them to accept only Letters from A-I I've created the method but that works for only one text box.
Here is my code:
textbox[i,j].Validated+=new EventHandler(TextBox_KeyPress);
private void TextBox_KeyPress(object sender, EventArgs e)
{
bool bTest = txtRegExStringIsValid(textbox[1,1].Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", textbox[1,1], 2000);
textbox[1,1].Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
Regex TheRegExpression;
string TheTextToValidate;
string TheRegExTest = #"^[A-I ]+$";
TheTextToValidate = textToValidate;
TheRegExpression = new Regex(TheRegExTest);
if (TheRegExpression.IsMatch(TheTextToValidate))
{
return true;
}
else
{
return false;
}
}
Can anyone please guide what should I do make this code work for all text boxes?
if this works for textbox[1,1] you could register your private void TextBox_KeyPress(object sender, EventArgs e) as eventhandler for all your textboxes and instead of textbox[1,1] you could use ((TextBox)sender)
i want text boxes to accept only letters from a-i actually i am trying to make sudoku
There's a much simpler solution than regular expressions, and you don't even need to handle the Validated event to implement it.
In a situation like this, where there are only certain characters that you want to prevent the user from entering, handling the KeyDown event is a much better solution. The user gets immediate feedback that the letter they tried to enter was not accepted. The alternative (the Validating and Validated events) actually wait until the user tries to leave the textbox to rudely alert them that their input was invalid. Especially for a game, this tends to break concentration and isn't particularly user-friendly.
Doing it this way also makes it irrelevant which individual textbox raised the event. Instead, you will handle it the same way for all of the textboxes—by completely ignoring all invalid input.
Here's what I'd do:
First, attach a handler method to your textbox's KeyDown event. You can do this from the Properties window in the designer, or you can do it through code, as you have in the question:
textbox[i,j].KeyDown += TextBox_KeyDown;
Then, you need to put the logic into your event handler method that determines if the key that the user just pressed is in the allowed range (A through I), or outside of it:
private void TextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Determine if the keystroke was a letter between A and I
if (e.KeyCode < Keys.A || e.KeyCode > Keys.I)
{
// But allow through the backspace key,
// so they can correct their mistakes!
if (e.KeyCode != Keys.Back)
{
// Now we've caught them! An invalid key was pressed.
// Handle it by beeping at the user, and ignoring the key event.
System.Media.SystemSounds.Beep.Play();
e.SuppressKeyPress = true;
}
}
}
If you want to restrict the user to typing in only one letter, you can add code to handle that in the above method, or you can take an even simpler route and let the textbox control handle it for you automatically. To do that, set the MaxLength property of the textbox to true, either in the designer or through code:
textbox[i,j].MaxLength = true;
Check the text of the sender instead of whatever textbox[1,1] is.
Use the sender parameter of the event handler to identify the textbox responsible for the event.
The first thing that will help you is casting the sender of your event to a TextBox like this:
(Also, as Cody Gray said, this is a TextBox_Validated event, not a KeyPress event so I've renamed it appropriately)
private void TextBox_Validated(object sender, EventArgs e)
{
TextBox tb = sender as TextBox()
if (sender == null)
return;
bool bTest = txtRegExStringIsValid(tb.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false) {
tip.Show("Only A-I", tb, 2000);
tb .ext = " ";
}
Next you need to actually get into that code for every textbox. There are two obvious approaches to that, you can either assign the eventhandler to each textbox in the array or you can use a custom textbox which always does this validation and then add that to your array.
Assign eventhandler to textboxes
foreach(var tb in textbox)
{
tb.Validated += new EventHandler(TextBox_KeyPress);
}
Create custom textbox control
Create the custom text box control (Add a user control to the project) and then just use it exactly as you would a normal textbox.
public partial class ValidatingTextBox: TextBox
{
public ValidatingTextBox()
{
InitializeComponent();
}
protected override void OnValidating(CancelEventArgs e)
{
bool bTest = txtRegExStringIsValid(this.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", this, 2000);
this.Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
// Exactly the same validation logic as in the same method on the form
}
}
In TextBox_Leave event i need to check whether numbers entered in textbox is in serial number or not.If it is not in order then i need to display a message as "number" is missing
For example :
In textbox i have entered 3 and click tab :
I need to display message as
"Number is not in order , number "1" and "2" is missing "
I don't know whether this also works in c#2.0, this is my experience in c#3.0:
Why do you use TextBox_Leave for that? The Validating-event should be used for validating whether input is correct.
Combine using the Validating-event with using an ErrorProvider (you can just drag it from the toolbox onto the form) to set an error message: it will be displayed as a (blinking) exclamation mark in a red triangle.
An ErrorProvider can also block any submit-actions.
One trick is to retain focus in the textbox when trying to leave (with TAB for instance) in case of some condition (missing number):
private void textBox1_Leave(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Text == "3")
tb.Focus();
}
Assuming you are using a standard textbox. You could also use third party controls that where you can cancel an event (e.Cancel = true) on some condition.
Try using a Masked TextBox control and set a custom property for this type of field validation.
Alternatively you can also use Validating event of the text box.
private void textBox1_Validating( object sender, CancelEventArgs e )
{
if ( textBox1.Text == "3" )
e.Cancel = true;
}
The text-box wont loose focus until it receives a valid input.
I will show you how to validate Validating WinForms TextBox (in C#).
Create a function:
public static void ChkBlankTextBoxes(object sender, string type)
{
if (sender is TextBox)
{
TextBox textbox = sender as TextBox;
if (string.IsNullOrEmpty(textbox.Text))
{
MessageBox.Show("Please enter correct value value..");
textbox.Focus();
}
}
}
Call to created function:
ChkBlankTextBoxes(txt_userID, textBoxtype);
ChkBlankTextBoxes(txt_password, textBoxtype);