I have a TextBox. After leaving the textBox the first character should be a capital Letter.
Three Events work as same. They are Leave,Validating and Validated.
if (txtLocl.Text.Length > 0)
txtLocl.Text = txtLocl.Text.Substring(0, 1).ToUpper() + txtLocl.Text.Substring(1);
Which event of these 3 events should I use?
You can subscribe to the Control.Leave event which will be fired when the control loses focus. Originally, I thought using Control.LostFocus would be the most appropriate event to use but it is not available via the designer meaning you would need to manually subscribe to the event which is a bit ugly and unconventional in my opinion.
private void inputTextBox_Leave(object sender, EventArgs e)
{
if (inputTextBox.Text != string.Empty)
{
string input = inputTextBox.Text;
inputTextBox.Text = input.First().ToString(CultureInfo.InvariantCulture).ToUpper() +
string.Join(string.Empty, input.Skip(1));
}
}
You sound like you're interested in Control.Validating. The advantage of using Control.Validating is that you can utilize the event handler's given argument; CancelEventArgs and set the Cancel property to true. What this will do is stop the control from losing focus and forcing the user to enter a valid value. I don't think this is appropriate for your application as you are not really validating anything but formatting the input.
private void inputTextBox_Validating(object sender, CancelEventArgs e)
{
if (inputTextBox.Text == string.Empty)
{
statusLabel.Text = "The given input is not valid.";
e.Cancel = true;
}
}
Bear in mind that when the form closes, all controls subsequently lose focus and the Control.Validating event is fired which could stop the Form closing until all fields pass their relative validation checks. If you find yourself needing to avoid this behavior a quick search will prevail.
There are many other events also available.
As said by MSDN, When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:
1) Enter
2) GotFocus
3) Leave
4) Validating
5) Validated
6) LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
1) Enter
2) GotFocus
3) LostFocus
4) Leave
5) Validating
6) Validated
If the CausesValidation property is set to false, the Validating and Validated events are suppressed.
textBox1_Leave is appropriate for you.
Check the events and description about textboxes over here>>
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox_events.aspx
Hope its helpful.
You might want to subscribe to LostKeyboardFocus event (in WPF) or Leave event (in WF).
I'd suggest using the Leave because I assume you aren't validating the value, but formatting it. Validating and Validated should contain code for validation and the aftermath of validation respectively, IMO.
Related
I'm developing a simple WPF application where I want to use the text changed method for a specific text field. the thing is I implemented the method but, the method gets fired in very short period, like even after i enter one character. I want to check whether the text change is completed in order to go with the methods written in the text changed method.
private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (...) // how to check whether the typing is finished?
{
// code goes here
}
}
I think you'll need the LostFocus event for this. As #SLaks comment says, you can't predict whether the user will press another key. Alternatively, you could databind the control - depending on what you're actually trying to do that may make more sense.
Instead of TextChanged, try monitoring the LostFocus event, which will fire when the user has left the textbox, either through pressing Enter/Tab or clicking somewhere else on the form.
Agree with LostFocus
UIElement.LostFocus Event
Question does not ask about binding but something to consider.
In binding the equivalent is UpdateSourceTrigger="LostFocus"
Binding.UpdateSourceTrigger Property
With binding you can get into more advanced validation UI effects.
How to: Implement Binding Validation
I've tried using the KeyUp and KeyDown events to read keyboard input but as soon as I place other controls on the Winform, the keys are not read. How do I make sure that the keys are read?
You could set KeyPreview = true on your form to catch keyboard events.
EDITED to let you understand:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
e.SuppressKeyPress = true;
}
Stupid sample that receives keyboard events and drop if A was pressed.
If focus is in a textbox, you'll see that text is written, but not A!!
EDITED AGAIN: I took this code from a VB.NET example.
In your usercontrol, use the text box's "Keypress" event to raise a "usercontrol event".
This code would be in your custom usercontrol:
'Declare the event
Event KeyPress(KeyAscii As Integer)
Private Sub Text1_KeyPress(KeyAscii As Integer)
RaiseEvent KeyPress(KeyAscii)
End Sub
See: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx
set KeyPreview = true and your KeyUp and KeyDown will recognize all keyboard input.
As marco says set KeyPreview to true on your form to catch the key events in the entire form rather than just a control.
Use the KeyPress event ... KeyUp/Down are more for the framework than your code. KeyDown is good if you want to disable a key ... numeric only fields etc. In general KeyPress is the one you're after.
If you want to prevent the keystrokes from propogating to other controls set KeyPressEventArgs.Handled = true.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
Have you wired up the event handler?
MyForm.KeyDown += MyHandler;
You can also do this in the properties pane ... click the event icon ...
If you are looking for your Form itself to read the keyboard input, you already have your answer from other correspondents. I am adding this contribution for the possibility that you might want to add key handling to other controls or user controls on your form. My article Exploring Secrets of .NET Keystroke Handling published on DevX.com (alas, it does require a registration but it is free) gives you a comprehensive discussion on how and why all the various keyhandling hooks and events come into play. Furthermore, the article includes a "Keystroke Sandbox" utility for free download that actually lets you see which controls are receiving which key handling events.
Here is one illustration from the article to whet your appetite:
Is there any event that fire when the value of the textbox change from a peace of code and when the textbox is validated or lost the focus and the event don't fire on the key press,because I have a lot of calculation and It's not possible to do it on every key press
Use TextChanged for text changed.
Use LostFocus for when textbox looses focus.
Use Validating or Validated for validation.
Here is the order in which events are called for TextBox:
// Reference : http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx
1) Enter
2) GotFocus
3) Leave
4) Validating
5) Validated
6) LostFocus
This should help you decide where you want to put your code.
There's no event that will fulfill your requirement of being raised when the textbox's value is changed programmatically through code, but not when text is typed into it by the user. The TextChanged event is going to be raised either way (this is fairly intuitive—the text value is changing, and the computer doesn't know or care what is responsible for changing it). As the documentation for this event indicates:
User input or setting the Text property to a new value raises the TextChanged event.
If you need to run custom validation logic when you add text to your textbox in code, you will need to invoke whatever method contains the validation logic yourself. Extract it into a separate method, which you call from the Validating/Validated event handler and from all of the places in your code where you set the textbox's Text property.
As a supplement to the other answers that have already been posted, I strongly recommend using either the Validating (if you want to be able to cancel the validation) or Validated events to handle the textbox losing focus, rather than the somewhat more obviously named LostFocus event.
You can use the LostFocus or Validated events.
Use a member variable.
private bool _changeByCode;
public void DoSomeChanges()
{
_changeByCode = true;
textbox1.Text = "Hello";
_changeByCode = false;
}
public void Textbox1_Change(object source, EventArgs e)
{
if (_changeByCode)
return;
//do your validation here.
}
I have a check box and I have subscribed for the CheckedChanged event. The handler does some operations in there. I check and uncheck the checkbox programmatically (ex: chkbx_Name.Checked = true), and the CheckedChanged event gets fired.
I want this event to be fired only when I manually check or uncheck it. Is there any way to avoid firing of this event when i check/uncheck it programmatically?
unsubscribe the event before you set:
check1.CheckChanged -= check1_CheckChanged;
then you can programmatically set the value without the checkbox firing its CheckChanged event:
check1.Checked = true;
then re-subscribe:
check1.CheckChanged += check1_CheckChanged;
[EDIT: March 29, 2012]
The problem with Tanvi's approach is you need to catch all source of manual check or uncheck. Not that there's too many(it's only from mouse click and from user pressing spacebar), but you have to consider invoking a refactored event from MouseClick and KeyUp(detecting the spacebar)
It's more neat for a CheckBox(any control for that matter) to be agnostic of the source of user input(keyboard, mouse, etc), so for this I will just make the programmatic setting of CheckBox really programmatic. For example, you can wrap the programmatic setting of the property to an extension method:
static class Helper
{
public static void SetCheckProgrammatically(
this CheckBox c,
EventHandler subscribedEvent, bool b)
{
c.CheckedChanged -= subscribedEvent; // unsubscribe
c.Checked = b;
c.CheckedChanged += subscribedEvent; // subscribe
}
}
Using this approach, your code can respond neatly to both user's mouse input and keyboard input via one event only, i.e. via CheckChanged. No duplication of code, no need to subscribe to multiple events (e.g. keyboard, checking/unchecking the CheckBox by pressing spacebar)
No. Those property change events fire whenever the property value changes, regardless of whether this was done by your code, by the control's own code or databinding. It's all the same code path, usually.
What you can do, however, if your event handler resides in the same class as the code that changes the property value, is to introduce a private boolean field in the class which you use as an indicator of whether the current property change is triggered by your code or by the user. After your change you simply reset it. The event handler would then look at the field and decide of whether it should do anything or not:
class Foo : Form {
private bool checkedProgrammatically = false;
void someMethod() {
// ...
checkedProgrammatically = true;
checkBox1.Checked = true;
checkedProgrammatically = false;
// ...
}
private void checkBox1_CheckChanged(object sender, EventArgs e) {
if (checkedProgrammatically) return;
// ...
}
}
I'm sorry I can't just comment on Michael Buen's answer due to my being new here (no reputation), but for what it's worth I strongly prefer his solution to Johannes Rössel's for a couple of reasons.
1) the checkedProgrammatically variable is a little too close to global for me. There's nothing to stop another method accidentally setting it to true, causing all your events to stop.
2) you could end up with a lot of variables depending on the number of events you're dealing with. It would be easy to change the wrong one and the results can be difficult to debug.
3) it's more obvious what you're doing when you unsubscribe then resubscribe. All the logic is right there, and you don't need to change your event handlers to exit early depending on certain conditions.
I've used both methods extensively and I find Michael's a lot easier in the long run.
You can use the MouseClick event and in that check for the checked state of the checkbox.
This way it wont be triggered programatically, it would only be called when the user manually checks or unchecks the checkbox.
You can set boolean variable before changing value programiticaly, and check than reset that variable in checkedchanged event
In WinForms I could handle the Validated event to do something after the user changed text in a TextBox. Unlike TextChanged, Validated didn't fire for every character change; it only fired when the user was done.
Is there anything in WPF I can use to get the same result, an event raised only after the user is done changing the text?
LostFocus will fire when the user moves from your textbox onto any other control.
It seems that there is no native solution.
The LostFocus event is a good idea. But when the user click on Enter, he wants the TextBox to validate the change.
So here is my suggestion : use the LostFocus event and the KeyDown event when the key is Enter.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
// code to lauch after validation
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// call the LostFocus event to validate the TextBox
((TextBox)sender).RaiseEvent(new RoutedEventArgs(TextBox.LostFocusEvent));
}
}
LostFocus is not equivalent to Validate. It creates lots of problem when you have multiple text boxes on one screen and every text box has some logic written in Validate. In validate event you can control focus easily but not in LostFocus so easily.
You can also try Binding.ValidationRules
Documented at : http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules.aspx
Here is the article to get started:
How to implement binding validations :
http://msdn.microsoft.com/en-us/library/ms753962.aspx