Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Silverlight » Working with DataGrid in Silverlight

Working with DataGrid in Silverlight

This article shows you how to work with a DataGrid control available in Silverlight 2.0. Article also demonstrates some formatting and data binding techniques.

Author Rank:
Total page views :  24947
Total downloads :  372
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DataGridBindingSample.zip
 
Become a Sponsor


Silverlight DataGrid Control

This article shows you how to work with a DataGrid control available in Silverlight 2.0. Article also demonstrates some formatting and data binding techniques.

Introduction

The DataGrid tag represents a Silverlight DataGrid control in XAML.  The DataGrid control is found in System.Windows.Controls namespace. When you drag and drop a DataGrid control from Toolbox to your XAML code, the action adds following tag for the DataGrid control.

 

<my:DataGrid></my:DataGrid>

 

And at the top of the XAML file, the designer adds the following line that adds a namespace System.Windows.Controls and assembly reference to System.Windows.Controls.Data.

 

xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

 

The Width and Height attributes represent the width and the height of a DataGrid.  The x:Name attribute represents the name of the control, which is a unique identifier of a control.  The Margin attribute sets the margin of the DataGrid being displayed from the top left corner.

 

The following code snippet sets the name, height, width, and margin of a DataGrid control.

 

<my:DataGrid x:Name="McDataGrid" Width="400" Height="300" Margin="10,10,10,10">           

</my:DataGrid>

 

Another way to create a DataGrid control is by dragging a DataGrid control from Toolbox to the XAML code in Visual Studio XAML editor.  Once you drag and drop a DataGrid control to the XAML page, you will see the following namespace reference is added to the XAML code.

 

xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

 

And the following code is added to the XAML code for the DataGrid.

 

<data:DataGrid></data:DataGrid>

 

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

 DataGridImg1.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.

Listing 1 sets the ItemsSource property of a DataGrid to an array of strings.

public MainPage()

{

    InitializeComponent();

    McDataGrid.ItemsSource = LoadStringData();

}

 

/// <summary>

/// Load a string collection

/// </summary>

/// <returns></returns>

private string[] LoadStringData()

{

    return "One Two Three Four Five Six Seven Eight".Split();

}

Listing 1

 

Figure 2 is the result of Listing 1. As you may see from Listing 1, the default column of the DataGrid shows all the strings in the array.

 DataGridImg2.gif

Figure 2

This was a simple example. Now let's build a little complex example.

ItemsSource and Data Binding

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. Right click on the project, select Add New Item and select Class. I give my class name Author.cs. After that, we are going to add some public properties to the class. The simplest way to add a property to a class is type "prop" and hit TAB twice. This action will add an automatic property to the class. See Figure 3.

DataGridImg3.gif

Figure 3

The final Author class looks like Listing 2.

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

 

The following code snippet sets the ItemsSource property of a DataGrid to List of Authors.

 

McDataGrid.ItemsSource = LoadCollectionData();

 

The new DataGrid looks like Figure 4, which shows the properties of the Author class a column names.

 

DataGridImg4.gif 

Figure 4

As you saw in Figure 4, 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 40 respectively.

<data:DataGrid x:Name="McDataGrid" Width="580" Height="270"

               Margin="10,10,0,0" Background="Bisque"

               ColumnWidth="100" RowHeight="40">           

   

</data:DataGrid>

The new DataGrid looks like Figure 5.

DataGridImg5.gif

Figure 5

 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 6.

DataGridImg6.gif

Figure 6

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 7.

DataGridImg7.gif

Figure 7

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 8.

DataGridImg8.gif

Figure 8

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 9.

DataGridImg9.gif

Figure 9

Summary

In this article, we learnt how to use a DataGrid control in Silverlight. I will add more DataGrid functionality to this article in my next update. If you developed any cool code and want to share here, feel free to post at the bottom.


Login to add your contents and source code to this article
 Article Extensions
Contents added by Mahesh Chand on May 03, 2009
How to get a Selected Row or Column or Cell Value in a WPF DataGrid?

SelectedItem property of DataGrid gives you the current selected item in the DataGrid in form of an object that is bound to the DataGrid. For example, if I have a collection of Author objects, which is defined as following:

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; }

}


The following code snippet will give me the current selected row and you can access the row data using the Author object. The following code snippet gives the Name column value from the DataGrid.

Author author = (Author)McDataGrid.SelectedItem ;

MessageBox.Show("Selected author: " + author.Name);


 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DataGridBindingSample.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Re: Canvas by fallonmassey On May 5, 2009
You probably would want a more flexible container than Canvas, otherwise, this is a nice intro article.
Reply | Email | Delete | Modify | 
Re: Re: Canvas by Mahesh On May 6, 2009
It was Grid by default but I need to set Left and Top margin :)
Reply | Email | Delete | Modify | 
The project looks like referring to SL3 and does not build by m On June 3, 2009
Hi !

Nice article, right for a beginner like me.
But the solution does not build ["Unable to read the project file 'DataGridBindingSample.csproj':The imported project .... SL 3 was not found].

Very sad. Any corrections posiibly??

br--mabra


Reply | Email | Delete | Modify | 
Re: The project looks like referring to SL3 and does not build by Mahesh On June 3, 2009
YES. SL2 does not have this control.
You need to download either SL3 or Silverlight Toolkit for SL2 to work it.
Reply | Email | Delete | Modify | 
Re: Re: The project looks like referring to SL3 and does not build by m On June 6, 2009
Hi !

Sad! I'll wait. But thanks for your demo and your reply!

br--mabra
Reply | Email | Delete | Modify | 
Column value from selected Row by Krishan On June 26, 2009
How we can fetch a column value of selected row on selectionchanged event
Reply | Email | Delete | Modify | 
Re: Column value from selected Row by Mahesh On July 21, 2009
I just added article extension that gives you the answer. Check it in the Article Extensions section.

How to get a Selected Row or Column or Cell Value in a WPF DataGrid?
Reply | Email | Delete | Modify | 
dynamically change the background colour of an individual DataGrid row by krishb2000 On July 13, 2009
Any Help would be greatly appreciated.
Reply | Email | Delete | Modify | 
Need to implement INotifyCollectionChanged? by jianchi On November 9, 2009
Nice example, but I don't see  implementation of INotifyCollectionChanged. How can the update of datasource flow to the bind-target?
It works for the initial load up, but when data source changes, datagrid is not updated. Or do I miss something?
Reply | Email | Delete | Modify | 
Re: Need to implement INotifyCollectionChanged? by Mahesh On November 9, 2009
Agree. I plan to work on two way data binding sample when get some free time. This was one way data binding sample.

Please do share your code if you end up fixing it.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.