Add/Edit/Delete DataGrid Using Master-Details View WPF

Add/Edit/Delete Introduction

In my previous article I have shown how to just display data from Database using the Linq to SQL. In this article I will show how to add, edit and delete the data from the datagrid in WPF using the Linq to SQL and BindingListCollectionView without much of the code behind coding.

Please note that I have used the Customers table of the Northwind database and I have used VS 2015 Community Edition for the Solution.

The data population of the datagrid is same as of the previous article. The only change which we have to do is that in place of ObjectDataProvider I will set the binding in the code behind and change the datagrid as shown below

And in the code behind I will set the DataContext of this page as the items which I will get from the CustomerDataContext class as shown below
Without showing each and every step to accomplish the Add/Edit/Delete functionality for the data using the master-detail pattern, I will directly show you the code behind file.
If we do any type of update(Add/Edit/Delete) in UI, the database will also be updated.

This is all we need to do accomplish this whole functionality.
And in the XAML part will be as shown below

For the ease of demo I have not taken all the columns of the table for the Details view. Now coming to the demo part, I will show how can update the details.

Add/Edit/Delete DataGrid

As we can see in the above figure, after running the project we get a window where we have DataGrid as Master and the fields below as Details.
Now as I have clicked on the first row of the grid, I can see the details of that row and Suppose I change the ContactName of this row to “Vikram” and click Save we will notice that the Contant name is changed in the Grid .

Editing details

And after saving the data, if we go to the database and run the query to see the results we will notice that data there is also changed as shown in the Below figure

Database updated

Similarly we can delete and add the data using the same way. For Adding you need to first click the Add Button and then Save it.

Conclusion

Here in this article I have shown you how easy it is to Add/Edit/Delete the data into the database using the BindingListCollectionVIew without hassel of writing queries and StoredProcedures.

The source code for Add/Edit/Delete is attached here

 

Vikram Chaudhary

I have 8 years of experience in developing .NET applications. I have worked on both web as well as windows based application using ASP.NET and WPF. I have keen interest in learning and implementing new things. You can always get in touch with me at vikram.chaudhary@dotnetforall.com or vikram.vee@outlook.com. Please let me know your thoughts about this article
  • Bhuven

    Hi Vikram, thank you for sharing

  • Aamir

    Hi GetAllCustomer is gving Exception ? How do i solve it