Click here to Skip to main content
15,943,077 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi people.
I have a DataGrid in WPF which name is "MyDataGrid"
It has 10 rows and 5 columns of data, and all of them are editable.
So whenever the user edits a cell, after pressing Enter, the focus will go to next row.
Please kindly help me that how may I disable this?
I mean how can I avoid the focus to go to next row, and keep that on the edited cell ?

What I have tried:

I couldn't find any solution sample yet.

Share this answer
Sh.H. 12-May-24 14:13pm
Thanks for reply.
Doesn't work.
Gives me exception.
Private Sub myDataGrid_CellEditEnding(sender As Object, e As DataGridCellEditEndingEventArgs) Handles myDataGrid.CellEditEnding
    KeyEventArgs.Handled = True
End Sub

Also I tried
e.Handled = True

but also did not work. 12-May-24 17:24pm    
You mixed DataGridCellEditEndingEventArgs and KeyEventArgs

My link to SO shows this:

private void PreviewKeyDown(object sender, KeyEventArgs e)
if ((e.Key.Equals(Key.Enter)) || (e.Key.Equals(Key.Return)))
e.Handled = true;

And use the related handler for PreviewKeyDown event !
Sh.H. 13-May-24 2:29am
I did what you shared in reply.
Now the problem is, when the user finishes editing on a cell, after pressing Enter, the cell is still in editing mode, and the user must use mouse clicking on another cell to finalize the editing. So I think disabling "Enter" is not a good idea. 13-May-24 5:42am    
You could try:

var selectedRow = myDataGrid.SelectedItem;

myDataGrid.CommitEdit(DataGridEditingUnit.Row, true);
myDataGrid.SelectedItem = selectedRow;

e.Handled = true;
Sh.H. 13-May-24 6:42am
Not worked.
This time, no keys able to press!
I mean when I start to type, the editing mode will close and cell goes empty.
I found this way, not as a solution, but it works.
Private Sub DGEditing_CellEditEnding(sender As Object, e As DataGridCellEditEndingEventArgs) Handles DGEditing.CellEditEnding
    Dim editedElement As FrameworkElement = TryCast(e.EditingElement, FrameworkElement)
    If editedElement IsNot Nothing Then editedElement.MoveFocus(New TraversalRequest(FocusNavigationDirection.Up))
End Sub

So I set FocusNavigationDirection to Up.
When the user finishes editing and press Enter, the focus will go down, and immediately goes up. So what the user see is the focus is still on the cell.

So the problem is as I have sub for event CurrentCellChanged, unfortunately with this code I wrote here, it fires two times. So anybody has any idea to improve this code?
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900