Deselect text in DataGridViewTextBoxCell after .CommitEdit(DataGridViewDataErrorContexts.Commit)

977 views Asked by At

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?

1

There are 1 answers

0
King King On

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 the EditingControlShowing event handler, here is the code:

//The EditingControlShowing event handler for your dataGridView1
private void dataGridView1_EditingControlShowing(object sender, 
                                          DataGridViewEditingControlShowingEventArgs e){
   var control = e.Control as TextBox;
   if(control != null && 
      dataGridView1.CurrentCell.OwningColumn.Name == "Interested Column Name"){
      control.TextChanged -= textChanged_Handler;
      control.TextChanged += textChanged_Handler;
   }
}
private void textChanged_Handler(object sender, EventArsg e){
  var control = sender as Control;
  if(control.Text == "interested value") {
     //disable your button here
     someButton.Enabled = false;
     //do other stuff...
  } else {
     someButton.Enabled = true;
     //do other stuff...
  }
}

Note that the conditions I used above can be modified accordingly to your want, it's up to you.