Better way to copy text in a textbox to datagridview

半世苍凉 提交于 2020-01-14 06:20:31

问题


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;
    }

回答1:


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();
}



回答2:


You may use the txtText_KeyPress event and see if the user pressed enter key (key code = 13).



来源:https://stackoverflow.com/questions/17396706/better-way-to-copy-text-in-a-textbox-to-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!