Sometimes while the user is typing text in a DataGridViewTextBox you want to enable or disable a control, depending on the value being typed. For instance enable a button after you typed a correct value
Microsoft showed the way in an article about how to create a DataGridViewButtonCell that can be disabled.
This is their trick (it can also be seen in other solutions)
- Make sure you get the event DataGridView.CurrentCellDirtyStateChanged
- Upon receipt of this event, commit the changes in the current cell by calling: DataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
- This commit will lead to the event DataGridView.CellValueChanged
- Make sure you get notified when this event is raised
- In your OnCellValueChanged function, check the validity of the changed value and decide whether to enable or disable the corresponding control (e.g. button).
This works fine, except that the CommitEdit makes that the text is selected while in OnCellValueChanged. So if you want to type 64, you get notified when you type 6 and later when you type 4. But because the 6 is selected you don't get 64, but the 6 is replaced by 4. Somehow the code must deselect the 6 in OnCellValueChanged before interpreting the value.
The property DataGridView.Selected doesn't do the trick, it doesn't deselect the text, but it deselects the cell.
So: how to deselect the text in the selected cell?
I think you need something that when the user is typing some text into the current cell, you need to know the current text (even before committing it) to check if some button need to be disabled. So the following approach should work for you. You don't need commit any thing, just handle the
TextChanged
event of the current editing control, the editing control is exposed only in theEditingControlShowing
event handler, here is the code:Note that the conditions I used above can be modified accordingly to your want, it's up to you.