-->

How can I dynamically detect the characters in a D

2019-09-16 19:55发布

问题:

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.