How to do the event handling when the user presses the ENTER key or leaves the focus on the particular textbox? I tried for KeyChanged event, but it will keep updating the number instead of only once when complete.
private void txtNumber_TextChanged(object sender, EventArgs e)
{
txtNumber.Text = double.Parse(txtNumber.Text).ToString("F2");
}
There are a few issues with the posted code. One issue is that doing the formatting each time the user “types” a character is going to be awkward for the user. In addition, if the user presses the “Enter” key, the event txtNumber_TextChanged is not going to fire. I assume you may already know this.
Next, when getting input from users, it is imperative that you check the input for valid numbers BEFORE calling the parse method…Example, the line of code…
double.Parse(txtNumber.Text).ToString("F2");
Will FAIL and crash the program if the text in the text box… txtNumber.Text is NOT a valid double.
You should always assume the user is going to make a mistake and you don’t want your code to crash when they do.
Therefore I suggest using the double.TryPasre method to avoid these possible crashes, calling this method will NEVER throw an exception and will make validating the number easier.
To get what you want I recommend you wire up three (3) events for the text box…
The Leave event, this is used to format the text, when the user leaves the text box, like when they click on another control.
Next is the PreviewKeyDown event, this is used when the user presses the “Enter” key.
And one extra event to help the user ONLY add numbers and one dot. The KeyPressed event is wired up and will ignore any pressed keys that are not numbers or the dot (period). Also, it will only allow one period, if the user tries to add a second decimal place, it will be ignored.
Bear in mind, the key pressed event helps by preventing the user from “typing” alpha text into the text box… however, the user can still paste text. Fortunately, since we are using the TryParse method, when the pasted text is an invalid number, the try parse will simply return “0.00” and NOT crash the code.
private void txtNumber_Leave(object sender, EventArgs e) {
double.TryParse(txtNumber.Text.Trim(), out double number);
txtNumber.Text = number.ToString("F2");
}
private void txtNumber_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
if (e.KeyCode == Keys.Enter) {
double.TryParse(txtNumber.Text.Trim(), out double number);
txtNumber.Text = number.ToString("F2");
}
}
private void txtNumber_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) // <- key pressed is not a control key
&& !char.IsDigit(e.KeyChar) // <- key pressed is not a digit (number)
&& e.KeyChar != '.') { // <- key pressed is not a dot (.)
e.Handled = true; // <- if its not a control key, digit or dot... then ignore it
}
// only allow one decimal point - if there is already a dot, then ignore the second one
if (e.KeyChar == '.' && txtNumber.Text.IndexOf('.') > -1) {
e.Handled = true; // <- if there is already a dot in the text... then ignore it
}
}
Formatting a text value in a TextBox must be done once the input is already done.
TextChanged, occurs when the Text property value changes. So this is not ideal.
The only event you can rely on.
LostFocus, occurs when the control loses focus. You can sheck some info when control change focus.
private void textBox1_LostFocus(object sender, System.EventArgs e)
{
// Code here
}
Sometimes we wanted the format to be changed once we click something on the keyboard, so here are the possible events for that.
The non-character keys do raise the KeyDown and KeyUp events.
KeyDown, occurs when a key is pressed while the control has focus.
KeyUp, occurs when a key is released while the control has focus.
KeyPress, occurs when a character. space or backspace key is pressed while the control has focus.
Note: When using the KeyPress you need to also consider if the Form is the one handling the input events first or not, check the Remarks here.
private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Return) // You can also use: e.KeyValue == 13
{
// Do your code here
}
};
Related
I have a user authentication form with username and password textboxes.There is an okay button that fires the code to validate the credentials.
I want the same code to get executed when the user hits Enter key anywhere on the form.
So i register for the keypress event like this
this.KeyPress += UserLogin_KeyPress;
private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
MessageBox.Show("enter");
}
}
This event is not triggered at all.What i'm i doing wrong?
Try setting the property keypreview to true and changing to keydown instead since KeyPress don't support e.Keycode:
private void UserLogin_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter");
}
}
Try this:
private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("enter");
}
}
As mentioned, set form.KeyPreview = true so that most key events will be given to the form before the controls.
However, note that this doesn't always work, and some controls will still "steal" certain key presses anyway. For example, if a Button has focus, then an Enter keypress will be used by the button to activate it, before you get a chance to see it, and since it counts as having been "handled", you never get to see the keypress.
The workaround I use for this is to set focus to something that I know will not steal the enter key press, for key presses that occur leading up to the enter key press. So, if the pressed keys are <1><2><3><4><ENTER> then the 1-4 keys all set focus to something that is not a button (usually, the textbox where I am displaying the resulting text), and then when <ENTER> is pressed, it should make it to your form's event handler (as long as KeyPreview == true).
It's only looking at the form. Controls on the form also need to be wired in.
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 need to determine whether a key, when it is pressed, will change the control's text or not; I need to ignore key presses like Ctrl+Z or Esc, but I need to know which key was pressed if the text changed.
Is there any way to know that in the KeyDown event? Currently, I'm using a flag, set on KeyDown and checked on TextChanged, but I was wondering if there is a better way?
You're looking for Char.IsControl
private Keys lastKey = Keys.None;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
lastKey = e.KeyData;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar))
{
e.Handled = true;//prevent this key press
Keys pressedKey = this.lastKey;
//Do your stuff with pressedKey here
}
}
You could catch the KeyPress event on the text box and if it is a valid key you would set e.handled = false and if it was a bad key you would set e.handled = true.
example from: here
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
}
}
There are some keys which produce a Control char but they also change the text, for example BackSpace. They have another difficulty: if the textbox is empty, pressing them (for example BackSpace) doesn't change the text; so it breaks the previous rule. So Control characters are not naive to deal with and build a rule upon.
Moreover, consider Ctrl + C or Shift + Insert or similar cases. The 'C' key is somehow seductive; it is like pressing 'C' changes the text but if it was pressed with 'Ctrl', it actually didn't change the text. We should check the Modifiers.
Perhaps you can find other difficulties to deal with and I think the flag approach is good enough.
I have the following code:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
}
}
When I press the N key , the selected text is replaced with "n". I read this Selecting text in RichTexbox in C# deletes the text ,but it had no effects.
I am using Windows Forms.
Likely, you will need e.Handled = true; in this to stop the event.
http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.handled.aspx
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.Handled = true;
}
}
Try it yourself:
Open up the editor, type some text, mark some of this text and press N. What happens? The marked text is replaced with n.
The same thing happens in your RichTextBox. Important to understand here is, that with the event you set up, you only add some functionality and leave the default event handling (handled by the OS) intact.
So with your code, on a key press you just do
richTextBox1.Select(1, 3);
which selects some characters and afterwards the default event handling kicks in. Thus there is some marked text which gets replaced with N.
So, you simply have to mark the event as handled by yourself. Not using the Handled-property, but with the SuppressKeyPress-property.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.SuppressKeyPress = true;
}
}
The documentation of Handled clearly states:
If you set Handled to true on a TextBox, that control will
not pass the key press events to the underlying Win32 text
box control, but it will still display the characters that the user typed.
Here is the official documentation of SuppressKeyPress.