Get Started with Data Grid

  • 6 minutes to read

Watch Video: Get Started with Data Grid

This tutorial describes how to build a simple Blazor application. The application uses a DevExpress Data Grid component to display and edit a weather forecast.

Get Started with Data Grid - Result

Create an Application

Refer to the Create an application section for instructions.

If you use Microsoft project templates, do the following:

  1. Configure the application as described in this topic: Microsoft Templates (Visual Studio).
  2. Apply the DevExpress Blazing Berry theme as described in this topic: Apply a DevExpress Bootstrap Theme.

Add a Data Grid and Bind It to Data

  1. Add <DxDataGrid></DxDataGrid> tags to the Pages/Index.razor page.

    <DxDataGrid>
    </DxDataGrid>
    
  2. In the Razor @code block, create a WeatherForecast class with Date, TemperatureC, CloudCover, and Precipitation fields.

    @code {
        public class WeatherForecast {
            public DateTime Date { get; set; }
            public int TemperatureC { get; set; }            
            public string CloudCover { get; set; }
            public bool Precipitation { get; set; }
        }
    }
    
  3. Declare a weatherForecasts observable collection. Fill this collection in the OnInitialized lifecycle method.

    @code {
        // ...
    
        static readonly Random random = new Random();
        readonly ObservableCollection<WeatherForecast> weatherForecasts = new ObservableCollection<WeatherForecast>();
    
        protected override void OnInitialized() {
            String[] CloudCover = {"Sunny", "Partly cloudy", "Cloudy", "Storm"};
    
            foreach (var date in Enumerable.Range(1, 30).Select(i => DateTime.Now.Date.AddDays(i))) {
                weatherForecasts.Add(new WeatherForecast() {
                    Date = date,
                    TemperatureC = random.Next(10, 20),
                    Precipitation = Convert.ToBoolean(random.Next(0, 2)),
                    CloudCover = CloudCover[random.Next(0,CloudCover.Length)]
                });
            }
        }
    }
    
  4. Use the Data property to bind the data grid to the weatherForecasts collection.

    <DxDataGrid Data="@weatherForecasts">
    </DxDataGrid>
    

Add Columns

Add the following objects to the markup and assign data source fields to them (use the Field property):

Column Data Source Field
DxDataGridDateEditColumn Date
DxDataGridSpinEditColumn TemperatureC
DxDataGridColumn CloudCover
DxDataGridCheckBoxColumn Precipitation

You can also set up the following properties to customize the columns:

<DxDataGrid Data="@weatherForecasts">
    <DxDataGridDateEditColumn Field="@nameof(WeatherForecast.Date)" 
                              DisplayFormat="D" 
                              EditorFormat="d" />
    <DxDataGridSpinEditColumn Field="@nameof(WeatherForecast.TemperatureC)" 
                              Caption="Temperature"
                              TextAlignment="DataGridTextAlign.Left" 
                              Width="100px" />
    <DxDataGridColumn Field="@nameof(WeatherForecast.CloudCover)" />
    <DxDataGridCheckBoxColumn Field="@nameof(WeatherForecast.Precipitation)" 
                              Width="100px" />
</DxDataGrid>

Get Started with Data Grid - Add columns

Edit Data

Follow the steps below to allow users to edit data:

  1. Add a DxDataGridCommandColumn column to the grid.
  2. Implement handlers for the following events to post the changes to the data source:

    NOTE

    The data grid is bound to the observable collection and automatically reloads data after changes. If you bind the data grid to a data source that does not implement the INotifyCollectionChanged interface, you should reload data and redraw the data grid after a row is inserted or deleted. To do this, use the Refresh method in the OnRowInserting and OnRowDeleting handlers.

  3. Implement a handler for the InitNewRow event to initialize a new data row.

<DxDataGrid Data="@weatherForecasts"
            InitNewRow="@OnInitNewRow"
            RowInserting="@((newValues) => OnRowInserting(newValues))"
            RowUpdating="@((updatingDataItem, newValues) => OnRowUpdating(updatingDataItem, newValues))"
            RowRemoving="@((dataItem) => OnRowDeleting(dataItem))">
    <DxDataGridCommandColumn />
    @*other columns 
    ...*@
</DxDataGrid>

@code {
    // declare the weatherForecasts collection
    // ...

    void OnRowInserting(Dictionary<string, object> itemProperties) {
        weatherForecasts.Add(UpdateItem(new WeatherForecast(), itemProperties));
    }
    void OnRowDeleting(WeatherForecast item) {
        weatherForecasts.Remove(item);
    }
    void OnRowUpdating(WeatherForecast item, Dictionary<string, object> itemProperties) {
        UpdateItem(item, itemProperties);
    }

    Task OnInitNewRow(Dictionary<string, object> values) {
        values.Add("Date", DateTime.Now);
        values.Add("TemperatureC", 13);
        values.Add("CloudCover", "Sunny");
        return Task.CompletedTask;
    }

    static WeatherForecast UpdateItem(WeatherForecast item, Dictionary<string, object> itemProperties) {
        foreach (var field in itemProperties.Keys) {
            switch (field) {
                case "Date":
                    item.Date = (DateTime)itemProperties[nameof(WeatherForecast.Date)];
                    break;
                case "TemperatureC":
                    item.TemperatureC = (int)itemProperties[nameof(WeatherForecast.TemperatureC)];
                    break;
                case "Precipitation":
                    item.Precipitation = (bool)itemProperties[nameof(WeatherForecast.Precipitation)];
                    break;
            }
        }
        return item;
    }
}

The command column contains buttons that allow users to manage rows.

Get Started with Data Grid - Manage rows

Sort Data

Use the following operations to sort data in the grid:

  • Click the Temperature column header to sort data against this column.
  • Click the Temperature and Precipitation column headers with the Shift key pressed to sort data against two columns.
  • Click the column headers with the Ctrl key pressed to clear sorting.

Get Started with Data Grid - Sort data

You can use the SortOrder and SortIndex properties to sort data in code.

<DxDataGridSpinEditColumn Field="@nameof(WeatherForecast.TemperatureC)" 
                          ...
                          SortOrder="DataGridColumnSortOrder.Descending" 
                          SortIndex="0" />
<DxDataGridCheckBoxColumn Field="@nameof(WeatherForecast.Precipitation)" 
                          ...
                          SortOrder="DataGridColumnSortOrder.Ascending"
                          SortIndex="1" />

Get Started with Data Grid - Sort order

Group Data

To enable users to group data, set the ShowGroupPanel property to true.

<DxDataGrid Data="@weatherForecasts"
            ...
            ShowGroupPanel="true">
</DxDataGrid>

To group data by a column, a user should drag the column header from the Column Header Panel and drop it onto the Group Panel.

Get Started with Data Grid - Group data

Filter Data

To enable users to filter data, set the ShowFilterRow property to true.

<DxDataGrid Data="@weatherForecasts"
            ...
            ShowFilterRow="true">
</DxDataGrid>

Get Started with Data Grid - Filter data

Complete Code

Show Complete Code
@page "/Index"
@using System.Collections.ObjectModel

<DxDataGrid Data="@weatherForecasts"
            InitNewRow="@OnInitNewRow"
            RowInserting="@OnRowInserting"
            RowUpdating="@OnRowUpdating"
            RowRemoving="@OnRowDeleting"
            ShowFilterRow="true"
            ShowGroupPanel="true">
   <DxDataGridCommandColumn></DxDataGridCommandColumn>
   <DxDataGridDateEditColumn Field="@nameof(WeatherForecast.Date)" 
                             DisplayFormat="D" 
                             EditorFormat="d"/>
   <DxDataGridSpinEditColumn Field="@nameof(WeatherForecast.TemperatureC)" 
                             Caption="Temperature" 
                             TextAlignment="DataGridTextAlign.Left"
                             Width="100px" 
                             SortOrder="DataGridColumnSortOrder.Descending" 
                             SortIndex="0"/>  
   <DxDataGridColumn Field="@nameof(WeatherForecast.CloudCover)" />
   <DxDataGridCheckBoxColumn Field="@nameof(WeatherForecast.Precipitation)" 
                             Width="100px"  
                             SortOrder="DataGridColumnSortOrder.Ascending" 
                             SortIndex="1"/>
</DxDataGrid>

@code {
   public class WeatherForecast {
       public DateTime Date { get; set; }
       public int TemperatureC { get; set; }
       public bool Precipitation { get; set; }
       public string CloudCover { get; set; }
   }    
   static readonly Random random = new Random();
   readonly ObservableCollection<WeatherForecast> weatherForecasts = new ObservableCollection<WeatherForecast>();

   protected override void OnInitialized() {
       String[] CloudCover = {"Sunny", "Partly cloudy", "Cloudy", "Storm"};

       foreach (var date in Enumerable.Range(1, 30).Select(i => DateTime.Now.Date.AddDays(i))) {
          weatherForecasts.Add(new WeatherForecast() {
              Date = date,
              TemperatureC = random.Next(10, 20),
              Precipitation = Convert.ToBoolean(random.Next(0, 2)),
              CloudCover = CloudCover[random.Next(0,CloudCover.Length)]
          });
       }
   }

   void OnRowInserting(Dictionary<string, object> itemProperties) {
       weatherForecasts.Add(UpdateItem(new WeatherForecast(), itemProperties));
   }
   void OnRowDeleting(WeatherForecast item) {
       weatherForecasts.Remove(item);
   }
   void OnRowUpdating(WeatherForecast item, Dictionary<string, object> itemProperties) {
       UpdateItem(item, itemProperties);
   }

   Task OnInitNewRow(Dictionary<string, object> values) {
       values.Add("Date", DateTime.Now);
       values.Add("TemperatureC", 13);
       values.Add("CloudCover", "Sunny");
       return Task.CompletedTask;
   }

   static WeatherForecast UpdateItem(WeatherForecast item, Dictionary<string, object> itemProperties) {
       foreach (var field in itemProperties.Keys) {
           switch (field) {
               case "Date":
                   item.Date = (DateTime)itemProperties[nameof(WeatherForecast.Date)];
                   break;
               case "TemperatureC":
                   item.TemperatureC = (int)itemProperties[nameof(WeatherForecast.TemperatureC)];
                   break;
               case "Precipitation":
                   item.Precipitation = (bool)itemProperties[nameof(WeatherForecast.Precipitation)];
                   break;
           }
       }
       return item;
   }
}

More Features

For the complete list of Blazor Data Grid features, refer to the following help topic: Feature List / Online Demos.