Dot Net For All

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

<DataGrid ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" Grid.Row="0" x:Name="dgCustomers"></DataGrid>

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.

 public partial class MainWindow : Window
    {
        bool isAdd = false;
        private BindingListCollectionView CustomerView;
        CustomerDataContext dc = new CustomerDataContext();
        public MainWindow()
        {
            InitializeComponent();
            var items = dc.GetAllCustomers();
            this.DataContext = items;
            this.CustomerView = (BindingListCollectionView)(CollectionViewSource.GetDefaultView(items));
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            this.dc.SubmitChanges();
            isAdd = false;
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            isAdd = true;
            Customer customer = (Customer)(this.CustomerView.AddNew());
            customer.CustomerID = "New";
            customer.ContactName = "";
            customer.City = "";
            customer.CompanyName = "";
            customer.Address = "";

            this.CustomerView.CommitNew();
            dgCustomers.ScrollIntoView(customer);

        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if(MessageBox.Show("Do you want to delete this customer?", "Delete", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
            {
                this.CustomerView.RemoveAt(this.CustomerView.CurrentPosition);
                this.dc.SubmitChanges();
            }

            isAdd = false;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if(isAdd)
            {
                CustomerView.CancelNew();
                CustomerView.Remove(this.CustomerView.CurrentItem);
            }
            else
            {
                CustomerView.CancelEdit();
                dc.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues);
                CustomerView.Refresh();
            }
        }
    }

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

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <DataGrid ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" Grid.Row="0" x:Name="dgCustomers"></DataGrid>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>

            <Label Content="ContactName" Grid.Row="0" Grid.Column="0" Margin="4"></Label>
            <Label Content="City" Grid.Row="1" Grid.Column="0" Margin="4"></Label>
            <Label Content="CompanyName" Grid.Row="2" Grid.Column="0" Margin="4"></Label>
            <Label Content="Address" Grid.Row="3" Grid.Column="0" Margin="4"></Label>

            <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Path=ContactName}" Margin="4"></TextBox>
            <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Path=City}" Margin="4"></TextBox>
            <TextBox Grid.Column="1" Grid.Row="2" Text="{Binding Path=CompanyName}" Margin="4"></TextBox>
            <TextBox Grid.Column="1" Grid.Row="3" Text="{Binding Path=Address}" Margin="4"></TextBox>

            <StackPanel Grid.Row="4" Grid.ColumnSpan="2" Orientation="Horizontal">
                <Button Content="Save" x:Name="Save" Click="Save_Click" Width="100" Margin="5"></Button>
                <Button Content="Add" x:Name="Add" Click="Add_Click" Width="100" Margin="5"></Button>
                <Button Content="Delete" x:Name="Delete" Click="Delete_Click" Width="100" Margin="5"></Button>
                <Button Content="Cancel" x:Name="Cancel" Click="Cancel_Click" Width="100" Margin="5"></Button>
            </StackPanel>
        </Grid>
    </Grid>

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.

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 .

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

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

Further Learning:

  1. WPF and MVVM: Advanced Model Treatment
  2. Practical MVVM
  3. Introduction to WPF custom controls

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview