StrataFrame Forum

How to stop TextBox_Leave event code from running

http://forum.strataframe.net/Topic29870.aspx

By Ger Cannoll - 4/11/2011

I have a form with a SearchTextBox on it, the only purpose of the SearchtextBox is to enter some text, then do a search, and populate other textBoxes on the form when you return from the search----- All working fine. The Search Results in a Grid being displayed, and a record can be selected.

I have the code to do the search on the SearchTextBox_Leave event.

My only probelm is that, if I have focus on the SearchTextBox, and I click on the X of the form to close the form, the Form Closes , but leaves a dangling search Grid on the screen, even though the Form itself is gone at this stage.

It probably does not matter , but the Grid happens to be a Devexpress grid which I use to do the searching. Is there a way to prevent the Code in the _Leave event from running, as I dont want it to run if the form has been released
By Greg McGuffey - 4/13/2011

The best thing to do is to override the ProcessCmdKey method in the sub-class. You can then run your search only when the user hits the Enter key (and maybe the tab key) within the textbox.  Here's some sample code:

public class SearchTextBox
  : TextBox
{

  public SearchTextBox() : base() { }

  /// <summary>
  /// Run search if enter is pressed while in the textbox.
  /// </summary>
  protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
  {
    //-- You could also define other keys, such as the tab key here.
    if (keyData == Keys.Enter)
    {
      //-- Run the search
      if (this.SearchFunction != null)
      {
        int count = this.SearchFunction( this.Text );
        MessageBox.Show( string.Format( "{0} items found" );
      }
      else
      {
        //-- Notify develper that they haven't setup a search function.
        MessageBox.Show( string.Format( "No search function defined. Search term is '{0}'", this.Text ) );
      }
    }

    //-- Whatever key is used to run the search
    //   should also just do whatever it normally does.
    return base.ProcessCmdKey( ref msg, keyData );
  }

  /// <summary>
  /// Define the function that runs the search. This
  /// function accepts a string search term and return
  /// number of items found. You could also use a
  /// normal delegate, so you don't have to have a return
  /// value. 
  /// </summary>
  public Func<string, int> SearchFunction { get; set; }

  /// <summary>
  /// Override to always return a string (and never null).
  /// </summary>
  public override string Text
  {
    get
    {
      string text = string.Empty;
      if (!string.IsNullOrEmpty( base.Text ))
      {
        text = base.Text;
      }
      return text;
    }
    set
    {
      base.Text = value;
    }
  }
}