Using DataGrid Control in WPF Application

Updated on     Kisan Patel

The DataGrid control can be used to showing a collection of objects in tabular form, with many customizations possible, programmatically.

In this tutorial, I will show you how to bind DataGrid from the collections and also how to work with DataGrid events and properties.

Lets create new WPF application and name it to “WpfDataGridDemo” then add a DataGrid to the existing Grid as shown in below code.

<Grid>
<DataGrid Name="grid_products" ItemsSource="{Binding}" />
</Grid>

Now, add a new class named Product as shown in below code.

Product.cs

public class Product
{
    public int Id { get; set; }

    public string ProductName { get; set; }

    public int Quantity { get; set; }

    public double Price { get; set; }

    public Uri ThumbUrl { get; set; }
}

Now, Open MainWindo.xaml.cs, add the following to the constructor, so that we have some product data and store into products variable.

Set the products variable as DataContext for the DataGrid. Here you can also get the data from the database but here we have add some static data to collections.

public MainWindow()
{
    InitializeComponent();

    var products = new List { 
        new Product{Id=1, ProductName="Product 1", Quantity=1, Price= 99.00, ThumbUrl = new Uri("images/product_1.jpg", UriKind.Relative)},
        new Product{Id=2, ProductName="Product 2", Quantity=2, Price= 199.00, ThumbUrl = new Uri("images/product_2.jpg", UriKind.Relative)},
        new Product{Id=3, ProductName="Product 3", Quantity=3, Price= 299.00, ThumbUrl = new Uri("images/product_3.jpg", UriKind.Relative)},
        new Product{Id=4, ProductName="Product 4", Quantity=4, Price= 399.00, ThumbUrl = new Uri("images/product_1.jpg", UriKind.Relative)},
        new Product{Id=5, ProductName="Product 5", Quantity=5, Price= 499.00, ThumbUrl = new Uri("images/product_2.jpg", UriKind.Relative)},
        new Product{Id=6, ProductName="Product 6", Quantity=6, Price= 599.00, ThumbUrl = new Uri("images/product_3.jpg", UriKind.Relative)}
    };

    grid_products.DataContext = products;
}

Now, Run the application. You should see a DataGrid with all the product details.

DataGrid-demo

Now, we have modified DataGrid as shown in below code to render the thumbnail image rather than url. Here, we have added a Columns property to the DataGrid.

<Grid>
   <DataGrid Name="grid_products" ItemsSource="{Binding}" >
       <DataGrid.Columns>
            <DataGridTemplateColumn Header="Thumbnail" >
                    <DataGridTemplateColumn.CellTemplate>
                          <DataTemplate>
                                <Image Margin="2" Width="32" Height="32"
                                        Source="{Binding ThumbUrl}" />
                          </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
       </DataGrid.Columns>
   </DataGrid>
</Grid>

Run the application. You should see the Thumbnail appearing as the first column.

DataGrid-demo-image

Here, the ThumbUrl Column also appears because we have not set AutoGenerateColumns value False as shown in below code:

<DataGrid AutoGenerateColumns="False" Name="grid_products" ItemsSource="{Binding}" >
       <DataGrid.Columns>
            <DataGridTemplateColumn Header="Thumbnail" >
                    <DataGridTemplateColumn.CellTemplate>
                          <DataTemplate>
                                <Image Margin="2" Width="32" Height="32"
                                        Source="{Binding ThumbUrl}" />
                          </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
       </DataGrid.Columns>
</DataGrid>

Run the application. You should see the Thumbnail appearing but all columns not appearing in DataGrid. So change AutoGenerateColumns property value to True or remove.

DataGrid-demo-AutoGenerateColumns

Now, lets add an event handler on the DataGrid for the AutoGeneratingColumn event. In the handler, add the following:

private void grid_products_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "ThumbUrl")
    {
        e.Cancel = true;
    }
}

These lines check if the DataGrid is currently generating the ThumbUrl column, and if so, cancel the operation. Running the application produces the following:

DataGrid-demo-AutoGeneratingColumn

The ThumbUrl column appears first. What if we wanted to show it last? Add another event handler for the DataGrid, AutoGeneratedColumns. This handler is called after all columns have been generated.

private void grid_products_AutoGeneratedColumns(object sender, EventArgs e)
{
     var grid = (DataGrid)sender;
     grid.Columns[0].DisplayIndex = 4;
}

Now, Run the application. The ThumbUrl column should be on the last.

DataGrid-demo-AutoGeneratedColumn

Download Complete Source Code


WPF

Leave a Reply