Event to prevent C# DataGridView from changing the current row
c#, datagridview, winforms
Solution
After trying lots of different things I came to the solution that the easiest and (for me) best working solution would be to check which control is focused in the `RowValidating` event of the `DataGridView`. This solution addresses exactly the problem I had: the `RowValidating` event was thrown by clicking other buttons for example. There are still some special cases which cause the `RowValidating` event to arise even if the current row isn't changing (sorting the `DataGridView` by clicking a column header, for example) but I think I can live with this minor issues. Maybe a future version of .NET will implement a `DataGridView` with a `RowLeaving` event which can be cancelled.
Problem
I would need an event that fires when the current row of a `System.Windows.Forms.DataGridView` is going to be changed and which allows me to cancel this change, e.g. by setting the Cancel-property of the EventArgs to true. I know about the `CurrentCellChanged` (the row has already changed when the event is called) and the `RowLeave` (no possibility to cancel the leave-operation) events, but neither provide what I would need. I also tried to use the `RowValidating` event, but this event is also called when the row is just going to be validated (without the intention to leave it), for example when I call `<ParentForm>.Validate()`, which leads to many confusions. Is there any other possibility or a clean(er) solution to get the desired behaviour?