开发者

What validation events are raised for the TextBox control?

开发者 https://www.devze.com 2023-02-02 03:10 出处:网络
Is there anyevent 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 lo

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 ever开发者_StackOverflow社区y 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.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消