How do I insert and update easily directly in DataGrid WPF with automatic saving?

Mojtaba_Hakim 326 Reputation points
2020-11-02T23:54:48.523+00:00

I'm using WPF C# and Entity Framework

I want to insert,delete,update directly in DataGrid in wpf project without anything else , just using DataGrid and KeyDown Event

So when insert or updating data in the cell after users press enter button or Tab button check the conditions for duplication next do it Save

Like this :
36806-gifs.gif

Developer technologies | Windows Presentation Foundation
SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. DaisyTian-1203 11,651 Reputation points Moderator
    2020-11-03T08:44:53.33+00:00

    You can add a KeyDown event in EventSetter for DataGridRow, like below code shown:

    <DataGrid.RowStyle>  
                    <Style TargetType="DataGridRow">  
                        <EventSetter Event="KeyDown" Handler="personDataGrid_KeyDown"></EventSetter>  
                    </Style>  
                </DataGrid.RowStyle>  
    

    And the code for updating is:

    private void personDataGrid_KeyDown(object sender, KeyEventArgs e)  
            {  
                try  
                {  
                    if (e.Key == Key.Enter || Key.Tab == e.Key)  
                    {  
                        e.Handled = true;  
                        Person newP = (sender as DataGridRow).Item as Person;  
      
                        //Delete the Old item from DB  
                        Person old = context.People.Where(t => t.ID.Equals(newP.ID)).FirstOrDefault();  
                        context.People.Remove(old);  
                        context.SaveChanges();  
      
                        //Check for duplication  and Add the new Items  
                        foreach (Person p in personDataGrid.Items)  
                        {  
                            if (p.ID != newP.ID) { context.People.Add(newP);  context.SaveChanges();}  
                        }  
                          
                    }  
                }  
                catch (Exception)  
                {  
                    throw;  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.