简体   繁体   中英

Better way to copy text in a textbox to datagridview

Good day!

I have this problem that every text change in the text box, selected item in the datagriview should copy its value. I have this code but it lags when I type(like very fast) in the textbox.

Is there any better way to do this w/o lagging?

Please help...

Here's what I have so far:

private void txtText_TextChanged(object sender, EventArgs e)
    {
        DataGridView1[2, pos].Value = txtText.Text;
    }

You may need to limit the number of events that are handled. Do your requirements allow you to use the TextBox Validated or LostFocus events instead?

If not you could look into Rx and throttle your TextChanged event. This can be achieved like so:

IObservable<EventPattern<EventArgs>> observable = Observable.FromEventPattern(
  txtText, "TextChanged").Throttle(TimeSpan.FromMilliseconds(500))
  .Subscribe(ep=> DataGridView1[2, pos].Value = txtText.Text;);

You could also throttle with a Timer .

Timer myTimer = new Timer();
myTimer.Interval = 500;
myTimer.Tick = OnTimerTick;

private void OnTimerTick(object o, EventArgs e)
{
  myTimer.Stop();
  DataGridView1[2, pos].Value = txtText.Text;
}

private void txtText_TextChanged(object sender, EventArgs e)
{
   if(!myTimer.Enabled) myTimer.Start();
}

您可以使用txtText_KeyPress事件,并查看用户是否按下enter键(键代码= 13)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM