将文本框中的文本复制到datagridview的更好方法

时间:2013-07-01 02:30:19

标签: c# winforms synchronization textchanged

美好的一天!

我有这个问题,文本框中的每个文本更改,datagriview中的选定项应该复制其值。我有这个代码但是当我在文本框中输入(就像非常快)时它会滞后。

有没有更好的方法来做这个没有滞后?

请帮忙......

这是我到目前为止所拥有的:

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

2 个答案:

答案 0 :(得分:3)

您可能需要限制处理的事件数。您的要求是否允许您使用TextBox ValidatedLostFocus事件?

如果没有,您可以查看Rx并限制TextChanged事件。这可以这样实现:

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

您还可以使用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();
}

答案 1 :(得分:0)

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