How can I dynamically detect the characters in a DataGridView cell? / Execute code after KeyDown returns and before KeyUp?

左心房为你撑大大i 提交于 2020-01-17 06:09:21

问题


How can I dynamically detect the characters in a DataGridView cell(while it is being edited)?

For example,

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

        }

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)

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

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.

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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/37505883/how-can-i-dynamically-detect-the-characters-in-a-datagridview-cell-execute-co

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