BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Display Controls - DataGrid - Editing

The one hundred and fifteenth part of the Windows Presentation Foundation Fundamentals tutorial continues the examination of the DataGrid control. This article looks at the basic data editing capabilities.

DataGrid

In the previous few article in the WPF tutorial we've looked at various features of the DataGrid control. We've seen the basics of creating a DataGrid and binding to a collection of objects, the available column types, sorting the data, resizing and reordering the columns, cell selection and formatting the grid using its properties.

So far in the tutorial we've only touched upon using DataGrids to allow the user to edit the information. In this article we'll look further at editing, and how to disable editing of the bound data. We'll do so using the example project that we've created in the earlier instalments. If you do not have an up-to-date version of the solution, you can download it using the link at the top of the article, "WPF Data Display Controls - DataGrid - Formatting". The project shows some details of the planets in the solar system.

Data Editing

By default, the data in a DataGrid is editable. The user can click a cell to enter edit mode, then enter a new value. The method for setting the new value is determined by the column type, or the template set for a templated column. For example, you can type a new value into a text column, select a value from a list for a combo box column or toggle a check box. The new value is stored in the bound property of the object that generated the data grid row, according to the binding expression used.

Data grids automatically provide the ability to add new rows and remove existing ones. When you add information to the blank, bottom row of a grid, a new object is added to the collection. The object is built using its default constructor before being added. To remove a row, you can select it by clicking the row header and pressing the Delete key. The corresponding object is then removed from the underlying collection.

To demonstrate, let's add a new button to the sample window and include code that shows the current data from the collection. Create a new button below the existing ones with the following XAML:

<Button Grid.Row="1" Width="100" HorizontalAlignment="Left"
        Click="ShowData_Click">Show Data</Button>

Add the following code behind the window to display the current planetary data.

private void ShowData_Click(object sender, RoutedEventArgs e)
{
    var data = new StringBuilder();

    foreach (var planet in DataContext as List<Planet>)
    {
        data.Append(planet.Name).Append(", Rings? ")
            .Append(planet.HasRings).Append(", Magnetic Field? ")
            .Append(planet.GlobalMagneticField).Append(", ")
            .Append(planet.Moons).Append(" Moon(s), ")
            .AppendLine(planet.Category);
    }

    MessageBox.Show(data.ToString());
}

Run the program and click the new button to see the data. Try editing the existing information, adding and removing planets, then clicking the button again. You should see that the changes that you make in the data grid are passed into the collection of objects.

Disabling Editing

You can disable the three key editing features of a data grid. To prevent the user from editing the grid at all, stopping them from changing values or adding or removing rows, set the DataGrid's IsReadOnly property to true. You can also apply this property to a column to prevent the user from editing the values in that column's cells.

Try editing the opening XAML tag for the DataGrid to make it read only:

<DataGrid Name="SampleGrid"
          ItemsSource="{Binding Source={StaticResource SortedPlanets}}"
          AutoGenerateColumns="False" Hyperlink.Click="DataGrid_Click"
          SelectionMode="Extended" SelectionUnit="CellOrRowHeader"
          RowHeaderWidth="20" ColumnHeaderHeight="35" RowHeight="25"
          Background="LightCyan" RowBackground="White"
          AlternatingRowBackground="Aquamarine"
          FrozenColumnCount="1"
          VerticalGridLinesBrush="LightBlue" GridLinesVisibility="Vertical"
          IsReadOnly="True">

Run the program to see the results. The empty row at the bottom of the grid will no longer be present, as it is only required to add new rows. It will also be impossible to switch cells into edit mode or delete an item from the collection.

Sometimes you will want to allow editing of the data but not permit new items to be added or existing rows to be deleted. You can disable those two features individually by setting one or both of the CanUserAddRows and CanUserDeleteRows properties to false.

To demonstrate, remove the IsReadOnly attribute and disable adding and removing rows:

<DataGrid Name="SampleGrid"
          ItemsSource="{Binding Source={StaticResource SortedPlanets}}"
          AutoGenerateColumns="False" Hyperlink.Click="DataGrid_Click"
          SelectionMode="Extended" SelectionUnit="CellOrRowHeader"
          RowHeaderWidth="20" ColumnHeaderHeight="35" RowHeight="25"
          Background="LightCyan" RowBackground="White"
          AlternatingRowBackground="Aquamarine"
          FrozenColumnCount="1"
          VerticalGridLinesBrush="LightBlue" GridLinesVisibility="Vertical"
          CanUserAddRows="False" CanUserDeleteRows="False">

Run the program again to see the results.

28 November 2014