c# - Delay reacting to TextChanged event -


i have winforms application reacts keystrokes in textbox using textchanged event. want delay reacting until there has been short gap (maybe 300 milliseconds) since last keystroke. below current code:

private void timerelapsed(object obj) {     if (textsearchstring.focused)      {  //this code throws exception         populategrid();         texttimer.dispose();         texttimer = null;     } }  private void textsearchstring_textchanged(object sender, eventargs e) {     if (texttimer != null)     {         texttimer.dispose();         texttimer = null;     }     texttimer = new system.threading.timer(timerelapsed, null, 1000, 1000); } 

my problem textsearchstring.focused throws system.invalidoperationexception.

what missing?

a system.threading.timer runs on background thread, means in order access ui elements must perform invocation or use system.windows.forms.timer instead.

i'd recommend system.windows.forms.timer solution easiest. no need dispose , reinitialize timer, initialize in form's constructor , use start() , stop() methods:

system.windows.forms.timer texttimer;  public form1() //the form constructor. {     initializecomponent();     texttimer = new system.windows.forms.timer();     texttimer.interval = 300;     texttimer.tick += new eventhandler(texttimer_tick); }  private void texttimer_tick(object sender, eventargs e) {     if (textsearchstring.focused) {         populategrid();         texttimer.stop(); //no disposing required, stop timer.     } }  private void textsearchstring_textchanged(object sender, eventargs e) {     texttimer.start(); } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -