SIGN UP MEMBER LOGIN:    
ARTICLE

DataGrid in WPF

Posted by Mahesh Chand Articles | WPF with C# September 28, 2009
This article is a part 1 of my WPF DataGrid series. In this part, you will learn how to create a DataGrid using XAML and C# and set its properties. The article will also show you how to apply data binding on a collection.
Reader Level:
Download Files:
 

This article shows you how to create and use a DataGrid control in WPF and XAML.

Note: This article is written using Visual Studio 2010 and .NET Framework 4.0.

Introduction

DataGrid element represents WPF DataGrid control in XAML.  

 

<DataGrid />

 

When you drag and drop a DataGrid control from Toolbox to your designer, position the control, this action adds following code to XAML.

 

The Width and Height properties represent the width and the height of a DataGrid.  The Name property represents the name of the control, which is a unique identifier of a control.  The Margin property sets the margin of placement of DataGrid on the window. The following code snippet sets the name, height, width, and margin of a DataGrid control.

 

<DataGrid Height="148" HorizontalAlignment="Left" Margin="12,21,0,0" 

          Name="dataGrid1" VerticalAlignment="Top" Width="225" />

                                                       Listing 1

 

Figure 1 shows Toolbox and XAML code preview after a DataGrid is added to a page.

 

 

WpfDataGridImg1.gif

Figure 1

 

Data Binding

The ItemSource property of DataGrid is the key to data binding. You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects.

In this example, we will create a collection of objects and bind it to a DataGrid control.

First, we are going to add a class to the project. The Author class looks like Listing 2 that has ID, Name, DOB, BookTitle, and IsMVP members.

public class Author

{

    public int ID { get; set; }

    public string Name { get; set; }       

    public DateTime DOB { get; set; }

    public string BookTitle { get; set; }

    public bool IsMVP  { get; set; }

}

Listing 2

 

Now let's create a collection of Author objects by using the List class. The LoadCollectionData method in Listing 3 creates a List of Author objects.

 

/// <summary>

/// List of Authors

/// </summary>

/// <returns></returns>

private List<Author> LoadCollectionData()

{

    List<Author> authors = new List<Author>();

    authors.Add(new Author(){

            ID = 101,

            Name = "Mahesh Chand",

            BookTitle = "Graphics Programming with GDI+",

            DOB = new DateTime(1975, 2, 23),

            IsMVP = false });

    authors.Add(new Author()

    {

        ID = 201,

        Name = "Mike Gold",

        BookTitle = "Programming C#",

        DOB = new DateTime(1982, 4, 12),

        IsMVP = true

    });

    authors.Add(new Author()

    {

        ID = 244,

        Name = "Mathew Cochran",

        BookTitle = "LINQ in Vista",

        DOB = new DateTime(1985, 9, 11),

        IsMVP = true

    });

    return authors;

}


Listing 3

 

Now the last step is to set ItemsSource property of DataGrid. The following code snippet sets the ItemsSource property of a DataGrid to List of Authors.

 

McDataGrid.ItemsSource = LoadCollectionData();

 

The data loaded in DataGrid looks like Figure 2, which shows the properties of the Author class a column names.

  

WpfDataGridImg2.gif

Figure 2

As you saw in Figure 2, all public properties of the Author object are represented as columns of the DataGrid. This is because by default, the AutoGenerateColumns property of DataGrid is true. If you do not wish to generate automatic columns, you simply need to set this property to false.

 

McDataGrid.AutoGenerateColumns = false;

 

Setting Column Width and Row Height

The ColumnWidth and RowHeight properties of DataGrid are used to set the default column width and row height of DataGrid columns and rows.

The following code snippet sets column width and row height to 100 and 30 respectively.

<DataGrid Height="200" Width="500" HorizontalAlignment="Left" Margin="12,21,0,0"

  Name="McDataGrid" VerticalAlignment="Top" RowHeight="30" ColumnWidth="100"

          >

The new DataGrid looks like Figure 3.

WpfDataGridImg3.gif

Figure 3

 The MaxWidth and MaxHeight properties represent the maximum width and maximum height of a DataGrid.  The MinWidth and MinHeight properties represent the minimum width and maximum height of a DataGrid. The MaxColumnWidth and MinColumnWidth properties represent the maximum width and minimum width of columns in a DataGrid.

Grid Lines Visibility and Header Visibility

The GridLinesVisibility property is used to make grid lines visible. Using this option you can show and hide vertical, horizontal, all, or none lines.  The HeaderVisibility property is used to show and hide row and column headers.

The following code snippet makes vertical grid lines visible and header visible for both rows and columns.

GridLinesVisibility="Vertical" HeadersVisibility="All"

The new DataGrid looks like Figure 4.

WpfDataGridImg4.gif

Figure 4

Grid Background, Row Background, and Alternative Row Background

The Background property is used to set the background color of the DataGrid. The RowBackground and AlternativeRowBackground properties are used to set the background color of rows and alternative of the DataGrid.

The following code snippet sets background, row background, and alternative row background colors of a DataGrid.

Background="LightGray" RowBackground="LightYellow"

AlternatingRowBackground="LightBlue"

The new DataGrid looks like Figure 5.

WpfDataGridImg5.gif

Figure 5

Border Color and Thickness

The BorderBrush and BorderThickness properties are used to set the color and width of the border. The following code snippet sets border color to gray and thickness to 5.

BorderBrush="Gray" BorderThickness="5"

The DataGrid with a new border looks like Figure 6.

WpfDataGridImg6.gif

Figure 6

Read Only and Freezing

The IsReadOnly property is used to make a DataGrid read only. That means you cannot edit a DataGrid. The following code snippet sets IsReadOnly property to true. 

IsReadOnly="True"

The AreRowDetailsFrozen property is used to freeze the row details area so it cannot be resized. The FrozenColumnCount property represents the number of columns that user can not scroll horizontally. The following code snippets sets AreRowDetailsFrozen to true and FrozenColumnCount to 2.

AreRowDetailsFrozen="True"

FrozenColumnCount="2"

 

DataGrid allows you to reorder columns by dragging a column but you may disable this feature by setting the CanUserReorderColumns property to false.  The following code snippet sets CanUserReorderColumns properties to false.

CanUserReorderColumns="False"

 

Data Grid allows you to change the width of columns. You may fix columns so user can't resize them by setting the CanUserResizeColumns property to false. The following code snippet sets CanUserResizeColumns properties to false.

CanUserResizeColumns="False"

Sorting

By default, column sorting is enabled on a DataGrid. You can sort a column by simply clicking on the column header.  You may disable this feature by setting CanUserSortColumns property to false. The following code snippet sets CanUserSortColumns properties to false.

CanUserSortColumns = "False"

Scrolling

The HorizontalScrollBarVisibility and VerticalScrollBarVisibility properties of type ScrollBarVisibility enumeration control the horizontal and vertical scrollbars of the DataGrid. It has four values - Auto, Disabled, Hidden, and Visible. The default value of these properties is Auto, that means, when scrolling is needed, you will see it, otherwise it will be hidden.

The following code snippet enables the horizontal and vertical scrollbars. 

HorizontalScrollBarVisibility="Visible"

VerticalScrollBarVisibility="Visible"

 

The DataGrid with both scrollbars looks like Figure 7.

WpfDataGridImg7.gif

Figure 7

Selection Mode

The SelectionMode property decides if the DataGrid allows only a single row or multiple rows selection. It has two values – Single and Extended.  The following code snippet sets the SelectionMode to Extended.

SelectionMode="Extended"


Summary

In this article, I demonstrated how to create a DataGrid control using XAML and how to set its properties and display data using a collection of objects. I also discussed how to format the DataGrid rows, columns, their visibility, and scrolling. We also saw, how to make rows read-only and set selection mode property.


I am working on several more part of this series and will publish as soon as I am done. My goal is write a complete book chapter on Just DataGrid control. If you have some cool code, any tips or article on WPF DataGrid, feel free to share here. 


 


Login to add your contents and source code to this article
share this article :
post comment
 

some assemblys don't work per default if you put there some additional assemblys, than write down how, where and the rest of the sh... because i don't get this peace of code that i have download here to work.

Posted by Mc Top Mar 21, 2012

I'm curious as to where the "McDataGrid.ItemsSource = LoadCollectionData();" goes.

Posted by Jamie Bowers Jan 26, 2012

Hi, Very use full article. For beginners in WPF like me can utilize it very well. Thanks a lot. I have some doubt on Datragrid's Readability after binding data from a standers source. I am binding datagrid to its Itemsource property from a Dataset which is linked to a Stored procedure Now based on a specific column's value i want to change the baground color of a row in this grid. after searching i could find ".Rows" property at all in the grid. And getting the specific Rows and column's value is impossible. we normally use "datagrid1.Rows[0].Cell[0].values" in c# code, Is there any substitute for this line in WPF DataGrid? can you please help me on this? Since we all need to bind data from Database through any specific source, and manipulate the data from DataGrid, if you could flash some lights on the topic for the correct path will be grate full. I hope you can. Thank you in advance Edwin

Posted by Edwin Danny Oct 03, 2011

Hi.. Thanks for the article. I have two Datagrids both bound to similar tables in a sql 08 db. What i am struggling to do is to select a row in lets say dgA and select a row in dgB. Then the Row in dgA updates the row in dgB Thanks

Posted by Tegan Theunissen Oct 02, 2011

Your WebService should be returning data in a string or XmlNode. You need to convert that to a collection such as an Array or load XmlNode to a DataTable or DataSet. Then you can direct bind it to the DataGrid.

Posted by Mahesh Chand Sep 08, 2011
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor