3
votes

I need to execute some logic if and only if the value of a particular cell changes AND the focus has shifted to another cell. The logic needs to be executed only if both a value has changed and the focus has changed...i.e. the user has finished editing a cell and is moving on. It should not go off just by changing the cell focus...only if the value was changed. I've been searching for and experimenting with events and have been unsuccessful so far.

Please note...this is an unbound grid view that is populated programmatically. I would have loved to have used a conventional bound grid view but this is what I have to use because of how our existing code is written.

This is what I have tried...

DataGridView.CellValidated "Occurs after the cell has finished validating." This fires when I change a cell value...and then afterwards every time I change cell focus regardless of if I actually change a cell value after the first time. Does not fit my needs because it keeps getting called whenever I move focus...even if there was not change in value.

DataGridView.CellValidating "Occurs when a cell loses input focus, enabling content validation." Does not seem to do what I need either.

DataGridView.CellValueChanged "Occurs when the value of a cell changes." This fires every time I change the value...before shifting focus. Not useful either for my purposes.

I really don't know if I am using the right event and or not setting a property somewhere or not calling a certain method to change the state of the grid view. Help would be appreciated.

Thanks, John

2
Perhaps someone can tell me why the question was down-voted so that I don't make whatever mistake I made here again? - JohnLaird

2 Answers

0
votes

Use the Cellvalidating event to check if the value has changed or not put it on globale Boolean and save the current cell row index and column, and on the SelectionChanged event check if the value change : if it hasn't change use DatagridCurrentCell to put the focus on the save index row and column saved

datagridview_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
  if(e.FormattedValue == (theOldValue))
  {
      changed = false; 
      currentIndexRow= e.RowIndex; 
      currentIndexColumn= e.ColumnIndex; 
      e.cancel = true; 

  }
}
datagridview_SelectionChanged(object sender, EventArgs e)
{
   if(!changed)
    datagridview.CurrentCell = datagridview.Rows[currentIndexRow].Cells[currentIndexColumn];
}
0
votes

Use a combination of events;
When a CellValueChanged event is fired, set a flag indicating that the value changed.
Then when the CellLeave event is fired, check the flag and execute your logic accordingly..