问题描述
如何动态地检测DataGridView单元中的字符(正在编辑中)?
How can I dynamically detect the characters in a DataGridView cell(while it is being edited)?
例如
我有一个带有DataGridView和TextBox的Winforms应用程序
I have a Winforms application with a DataGridView and a TextBox
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is TextBox)
{
var tbox = (e.Control as TextBox);
// De-register the event FIRST so as to avoid multiple assignments (necessary to do this or the event
// will be called +1 more time each time it's called).
tbox.KeyDown -= DGV_TextBoxKeyDown;
tbox.KeyDown += DGV_TextBoxKeyDown;
}
}
private void DGV_TextBoxKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
textBox1.Text = dataGridView1.CurrentCell.EditedFormattedValue.ToString();
}
我拥有的代码晚了一个字符,因此例如,如果我键入abcde,则文本框将显示abcd.我希望它显示abcde(我不希望它迟到一个字符)
The code I have is one character late, so for example if I type abcde, then the textbox displays abcd. I want it to display abcde (I don't want it to be one character late)
但是我不想通过附加被按下的键来做到这一点,因为如果我键入abcde并删除"b",那么我希望文本框显示它的名称.因此,我希望能够读取当前值(按下按键后的值)(以及按下按键前的值),但是我看不到
But I don't want to do it by appending the key that was pushed, because if I type abcde and delete the 'b' then I want the textbox to show it's acde. So I want to be able to read the current value(the value after the key has been pushed down), (and before the key has been pushed up), but I can't see how
请注意文本框如何过时.,同样在下面,它已经过时了,我输入abcde并删除'b'.只能从按下键之前获得旧的编辑值.
Notice how the textbox is out of date., and likewise below, it's out of date, I type abcde and delete the 'b'. It is only getting the old edited value from before the key was pushed down.
我不想在按键上进行操作,因为例如举起一个按键,例如10秒钟然后抬起,然后将有10秒钟的延迟才能更新文本框.我真的很希望这样,只要键入一个字符,文本框就会更新.
I don't want to do it on key up because if for example a key is held for e.g. 10 seconds and lifted, then there would be a 10 seconds delay before the textbox will be updated. I really want it such that any time a character is typed, the textbox updates.
我知道,如果按住某个键,则keydown会执行多次.如果我能够在KeyDown返回之后和KeyUp之前执行代码,那么我可以检查dataGridView1.CurrentCell.EditedFormattedValue.ToString();
,然后应该这样做.但是我不知道怎么办.
I know that if a key is held, then keydown executes multiple times. If I was able to execute code after KeyDown returns, and before KeyUp, then I could check dataGridView1.CurrentCell.EditedFormattedValue.ToString();
then, and that should do it. But I don't know how.
推荐答案
我怀疑可能有什么事情使事情变得不那么简单,但是毕竟您可以将.TextChanged
事件与文本框中的文本一起使用DGV,并在每次更改时更新另一个TextBox的值.
I had the suspicion that there could be anything that makes it not that simple, but after all you could just use the .TextChanged
event with the textbox in the DGV and update the value of the other TextBox on each change.
这篇关于如何动态检测DataGridView单元中的字符? /在KeyDown返回之后和KeyUp之前执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!