Skip to main content

Lesson 3 - Post Changes to a Database

  • 2 minutes to read

This tutorial demonstrates how to edit data within the GridControl and save changes to the database. The tutorial is based on Lesson 2.

The Items Source Wizard adds the post data functionality when you enable the CRUD (Create, Read, Update, Delete) options.

Items Source Wizard - Settings

The Items Source Wizard generates the following code:

  1. Sets the TableView.ShowUpdateRowButtons property to OnCellEditorOpen. This property turns on an edit mode that allows users to edit an entire row and then submit or cancel all changes at once:

    GridControl Tutorial Edit Entire Row

  2. Sets the TableView.NewItemRowPosition property to Top. The New Item Row allow users to add new rows to the GridControl:

    GridControl Tutorial New Item Row

  3. Creates the following commands that are generated at runtime from methods with the Command attribute. The generated command name follows the [MethodName]Command pattern.

    The ValidateRow command adds new rows and saves changes to the database:

    [Command]
    public void ValidateRow(RowValidationArgs args) {
        var item = (Order)args.Item;
        if (args.IsNewItem)
            _Context.Orders.Add(item);
        _Context.SaveChanges();
    }
    

    The ValidateRowDeletion command removes items from the database:

    [Command]
    public void ValidateRowDeletion(ValidateRowDeletionArgs args) {
        var item = (Order)args.Items.Single();
        _Context.Orders.Remove(item);
        _Context.SaveChanges();
    }
    

    The DataSourceRefresh command fetches changes from the database and updates grid content:

    [Command]
    public void DataSourceRefresh(DataSourceRefreshArgs args) {
        _ItemsSource = null;
        _Context = null;
        RaisePropertyChanged(nameof(ItemsSource));
    }
    

    TableView properties are bound to generated commands:

    <dxg:GridControl x:Name="grid" ItemsSource="{Binding Orders}">
        <!-- ... -->
        <dxg:GridControl.View>
            <dxg:TableView NewItemRowPosition="Top"
                           ShowUpdateRowButtons="OnCellEditorOpen"
                           ValidateRowCommand="{Binding ValidateRowCommand}"
                           ValidateRowDeletionCommand="{Binding ValidateRowDeletionCommand}"
                           DataSourceRefreshCommand="{Binding DataSourceRefreshCommand}"/>
        </dxg:GridControl.View>
    </dxg:GridControl>
    

    The Delete key removes selected rows from the GridControl:

    <dxg:GridControl.InputBindings>
        <KeyBinding Command="{Binding View.Commands.DeleteFocusedRow, ElementName=grid}" Key="Delete"/>
    </dxg:GridControl.InputBindings>
    
See Also