delaying TextBox.TextChanged event

  • Thread starter Thread starter VMI
  • Start date Start date
V

VMI

I'm trying to some dynamic searching to my windows Form so I added code in
my TextBox.TextChanged so that, after every text change, a search is done to
a datatable. So if I want to type the string "Memphis", it'll do a search
(and display) all the items after the user types "M", then another search
(of "Me") when the user types "e", another search of "Mem" after "M", and so
on. The problem is that there's so much data in the table that each one of
these searches is very slow, and I can't use a primary key because it
searches in all columns (there's three).
Is there any way that I can delay the TextChange so it only executes if the
user doesn't type anything for, say, a second? Or is there any way I can do
this?

Thanks.
 
One idea would be to have a timer object on the form set to the time you
want to the delay to be.

From here you could reset the timer everytime a valid key is pressed,
changing the value of your textbox. If the event of the timer fires, and you
have some text then I'd advise starting another thread to populate your
datatable.

You need to be careful of things like, what happens when you press a key
while the thread is busy populating the data table... clearly the thread
will have to be aborted before the new one can start, otherwise you'll have
two threads trying to populate the same datatable.

If you want to read up on multithreading, Jon Skeet's got a good article on
it:
http://www.yoda.arachsys.com/csharp/threads/

A complete alternative to all this is scrap the idea of searching after each
key press, even with a delay, and having a find button. This method holds
more weight, especially since you have a large dataset with no efficient way
of searching it.

Just hallow if you need any help.
 
One suggestion is to use the System.Timers.Timer like so:

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}

System.Timers.Timer timer = new System.Timers.Timer( 500 );
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
timer.Stop();
timer.Start();
}

private void timer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
Console.WriteLine( "Do something here." );
}

If you were getting really excited about it, you could write an
IExtenderProvider component to so you could easily add this
functionality to any textbox...
 
Back
Top