Udemy logo

c# datagridC# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft. It is part of the .NET framework. If you know C, C++ or Java, then you can learn C# easily. DataGrid is the construct used to represent and process data in C#. In this intermediate level tutorial, we walk you through C# DataGrid.

We assume that you know the basics of C# and XAML. If you’re new to programming, you may first want to take this beginners course on C#.

What is DataGrid?

A DataGrid is a table which has rows and columns. DataGrid is useful to present and edit tabular data. Properties of DataGrid are used to populate it. We can specify how users edit its data and how it visually renders that data.  You can adjust its appearance, react to its events and populate its contents. It is indeed a powerful and commonly needed control to handle and manipulate data in C#. You can explore more about DataGrid with this great course on C# fundamentals.

What is XAML

XAML or Extensible Application Markup Language is an XML based markup language created by Microsoft. It is used for describing a GUI. In previous GUI frameworks a GUI was created in the same language that was used to interact with the GUI. Also it was usually maintained by the designer. That is not the case here.  Here just like with HTML, you can easily write and edit your GUI. Whether you create a Window or a Page, it will comprise of a XAML document and a CodeBehind file. The XAML file will describe the user interface with all its elements and the CodeBehind will handle all the events and has access to manipulate the XAML controls. To learn more about XML, go can take this introductory course.

Now that we have the basics in place, lets take a look at how DataGrids work, with some  examples.

Example 1: Program to Handle the Loading of a DataGrid Event

The XAML part:

<Window x:Class="WpfApplication14.MainWindow"

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="MainWindow" Height="350" Width="525">

    <Grid>

     <DataGrid

         HorizontalAlignment="Left"

         Margin="10,10,0,0"

         VerticalAlignment="Top"

         Loaded="DataGrid_Loaded"/>

    </Grid>

</Window>

The C# part

 using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

 class Cat

{

    public string Name { get; set; }

    public int Size { get; set; }

     public Cat(string name, int size)

    {

     this.Name = name;

     this.Size = size;

    }

}

 namespace WpfApplication14

{

    public partial class MainWindow : Window

    {

     public MainWindow()

     {

         InitializeComponent();

     }

      private void DataGrid_Loaded(object sender, RoutedEventArgs e)

     {

          var items = new List<Cat>();

         items.Add(new Cat("Tom", 10));

         items.Add(new Cat("Blacky", 20));

         items.Add(new Cat("Pasha", 4));

           var grid = sender as DataGrid;

         grid.ItemsSource = items;

     }

    }

}

In this program, the datagrid and its property ItemSource with a List is used. Initially, create a WPF project and drag a DataGrid Control to your window. In the XAML code add the attribute “Loaded” to the DataGrid element. When you do this, Visual studio will create the DataGrid_Loaded event handler. In this function, we assign the ItemSource property. In the DataGrid_Loaded method we create a List of cat objects. Note that the DataGrid automatically traverses this objects.

The xmlns attribute specifies the xml namespace for a document. In Windows Forms, programs are created visually. Controls are dragged to the Form in Visual Studio. The Latter adds code to the initializeComponent method, which is called in the Form constructor.

In the Cat class, there are two public properties: Name(a string) and Size( an int). Each property becomes a column header in the resultant DataGrid. So the DataGrid has Name and Size columns.  To learn more about the Cat class, you can take this intermediate C# course.

Example 2: Program to Change the Background of a DataGrid

 <Window x:Class="WpfApplication14.MainWindow"

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

     Title="MainWindow" Height="350" Width="525">

    <Grid>

     <DataGrid

         HorizontalAlignment="Left"

         Margin="10,10,0,0"

         VerticalAlignment="Top"

         AlternatingRowBackground="Blue"

         Loaded="DataGrid_Loaded"/>

    </Grid>

</Window>

Sometimes a grid is hard to read. Using the DataGrid’s AlternatingRowBackground attribute we can make the rows of the grid easier to read. We set  AlternatingRowBackground=”Blue”. You can look up more about DataGrids and their properties in this advanced C# course.

 Example 3: Program to Access the Selected Cells in a DataGrid

code: XAML

 <Window x:Class="WpfApplication14.MainWindow"

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

     Title="MainWindow" Height="350" Width="525">

    <Grid>

     <DataGrid

         HorizontalAlignment="Left"

         Margin="10,10,0,0"

         VerticalAlignment="Top"

         SelectionChanged="DataGrid_SelectionChanged"

         Loaded="DataGrid_Loaded"/>

    </Grid>

</Window>



code: C#

 using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

 class Cat

{

    public string Name { get; set; }

    public int Size { get; set; }

     public Cat(string name, int size)

    {

     this.Name = name;

     this.Size = size;

    }

}

 namespace WpfApplication14

{

        public partial class MainWindow : Window

    {

     public MainWindow()

     {

         InitializeComponent();

     }

      private void DataGrid_Loaded(object sender, RoutedEventArgs e)

     {

         var items = new List<Cat>();

         items.Add(new Cat("Fido", 10));

         items.Add(new Cat("Spark", 20));

         items.Add(new Cat("Fluffy", 4));

         items.Add(new Cat("Rover", 100));

         items.Add(new Cat("Mister Mars", 30));

              var grid = sender as DataGrid;

         grid.ItemsSource = items;

     }

      private void DataGrid_SelectionChanged(object sender,

         SelectionChangedEventArgs e)

     {

         var grid = sender as DataGrid;

         var selected = grid.SelectedItems;

              List<string> names = new List<string>();

         foreach (var item in selected)

         {

          var cat = item as Cat;

          names.Add(cat.Name);

         }

        this.Title = string.Join(", ", names);

     }

    }

}

In this program, we look at how to access the selected cells in a DataGrid. Using the SelectedItem property in XAML we get a list of these cells. In this example we populate the DataGrid with a list of Cat objects. To handle the SelectionChanged event we add the DataGrid_SelectionChanged method. Here we loop over the items in the selected items list. In the end we cast each object to its original type which is the Cat type. Then we join these strings together and display them on the window.

Example 4: Program to Edit the Cells of the DataGrid

code: XAML

<Window x:Class="WpfApplication14.MainWindow"

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

     Title="MainWindow" Height="350" Width="525">

    <Grid>

     <DataGrid

         HorizontalAlignment="Left"

         Margin="10,10,0,0"

         VerticalAlignment="Top"

         CellEditEnding="DataGrid_CellEditEnding"

         Loaded="DataGrid_Loaded"/>

    </Grid>

</Window>

Code : C#

private void DataGrid_CellEditEnding(object sender,

    DataGridCellEditEndingEventArgs e)

{

   var element = e.EditingElement as TextBox;

    var text = element.Text;

    if (text == "?")

    {

     this.Title = "Invalid";

     e.Cancel = true;

    }

    else

    {

     this.Title = "You typed: " + text;

    }

}

 

The DataGrid Control lets users edit its cells. When the user finishes the edit operation the CellEditEnding event is triggered. Here in the C# method we can cancel the edit. This is particularly useful in case of an invalid entry. Note that we have used the same program as in previous examples, but omitted certain repeated parts of the source file. Here we set the cancel property on the DataGridCellEditEndingEventArgs to true. By this action the edit applied by the user to the cell will be rejected.

Example 5: Program to Scroll the DataGrid

 using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

 class Order

{

    public int Size { get; set; }

}

 namespace WpfApplication14

{

    public partial class MainWindow : Window

    {

     public MainWindow()

     {

         InitializeComponent();

     }

      private void DataGrid_Loaded(object sender, RoutedEventArgs e)

     {

              var items = new List<Order>();

         for (int i = 0; i < 100; i++)

         {

          items.Add(new Order { Size = i });

         }

              var grid = sender as DataGrid;

         grid.ItemsSource = items;

               grid.ScrollIntoView(items[items.Count - 1]);

     }

    }

}

Note that several functions of the DataGrid control can be automated. One of the features of this control is support for scrolling. In order to get this functionality we have to use the ScrollIntoView method. Please specify the object used as the source of the row which is part of the ItemsSource IEnumerable collection. In this example we add 100 objects to a list and use that with  ItemsSource. Finally, we scroll to the final element in the collection. In other words we scroll to the last row.

Hope this tutorial was useful and fun. Do try out your own code and experiment with it. That’s the best way to master any programming language. You may even want to try your hand at creating your own Android App in C#, with this course.

Page Last Updated: April 2014

Top courses in C# (programming language)

Design Patterns in C# Made Simple
Zoran Horvat
4.7 (404)
Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (40,269)
Bestseller
Ultimate C# Masterclass for 2024
Krystyna Ślusarczyk
4.7 (1,031)
Bestseller
Learn Parallel Programming with C# and .NET
Dmitri Nesteruk
4.4 (3,537)
Bestseller
Unity RPG Inventory Systems Asset Pack: Behind The Scenes
GameDev.tv Team, Rick Davidson
4.4 (837)
Advanced Topics in C#
Dmitri Nesteruk
4.5 (555)
C#/.NET - 50 Essential Interview Questions (Mid Level)
Krystyna Ślusarczyk
4.8 (206)
Bestseller
Complete C# Masterclass
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.6 (27,247)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.4 (11,223)
Bestseller
C# 10 | Ultimate Guide - Beginner to Advanced | Master class
Web University by Harsha Vardhan
4.6 (2,981)

More C# (programming language) Courses

C# (programming language) students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo