问题
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