Skip Navigation LinksHome / Articles / View Article

Introduction to the DataGrid control in Silverlight 2

+ Add to SilverlightShow Favorites
18 comments   /   posted by Martin Mihaylov on Sep 11, 2008
(7 votes)
Categories: Learn , Tutorials , QuickStarts

Update: The source codes and the information in this article are compatible with Silverlight 2 RTW.

This is the first of series of articles about the DataGrid control. In it I'll introduce you to the basics of the controls how to add data to it and how to define its columns. With every next article I'm going to add something new to this example and keep extending it with cool things, so at the end there will be a lot of information about the DataGrid, some Tips and Tricks and a lot of source code and demos. Now let's start with the basics and don't be impatient - soon the things will get very interesting!

Adding a DataGrid control

From the ToolBox we drag and drop a Datagrid control into the Xaml. The first thing that will make an impression to you is the tag and the "my" prefix:

<my:DataGrid x:Name="Foods"></my:DataGrid>

That's because the DataGrid is found in the System.Windows.Controls namespace. If you take a look at your UserControl tag you'll see that a declaration for this namespace was generated in it:

<UserControl x:Class="DataGrid.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"     
    Width="400" Height="300">

Configuring the columns

For now we use the ability of the DataGrid to auto generate columns for each property of the source object. We do that by setting the AutoGenerateColumns property to true. Later we'll see how to manually define the columns:

<my:DataGrid x:Name="Food" AutoGenerateColumns="True"></my:DataGrid>

Adding some data

What is the DataGrid without a data in it? Nothing, so let's add some data. For my examples I will use the same information Emil has used in his article about Creating a simple Pivot table using LINQ and RadTreeView for Silverlight, namely the nutrition that are contained in the pizza. Let's start with creating the Xml file:

 

and it contains:

<?xml version="1.0" encoding="utf-8" ?>
<Nutritions>
    <Nutrition Group="Carbohydrates" Name="Total carbohydrates" Quantity="27.3"></Nutrition>
    <Nutrition Group="Carbohydrates" Name="Total disaccharides" Quantity="5.7"></Nutrition>
    <Nutrition Group="Carbohydrates" Name="Total polysaccharides" Quantity="21.6"></Nutrition>
    <Nutrition Group="Minerals" Name="Calcium" Quantity="147"></Nutrition>
    <Nutrition Group="Minerals" Name="Phosphorus " Quantity="150"></Nutrition>
    <Nutrition Group="Minerals" Name="Potassium " Quantity="201"></Nutrition>
    <Nutrition Group="Minerals" Name="Copper " Quantity="0.13"></Nutrition>
    <Nutrition Group="Minerals" Name="Magnesium " Quantity="19"></Nutrition>
    <Nutrition Group="Minerals" Name="Sodium " Quantity="582"></Nutrition>
    <Nutrition Group="Minerals" Name="Selenium " Quantity="4"></Nutrition>
    <Nutrition Group="Minerals" Name="Total iron " Quantity="0.7"></Nutrition>
    <Nutrition Group="Minerals" Name="Zinc" Quantity="1.07"></Nutrition>
    <Nutrition Group="Vitamins" Name="Beta-carotene " Quantity="173.8"></Nutrition>
    <Nutrition Group="Vitamins" Name="Nicotinic " Quantity="1.5"></Nutrition>
    <Nutrition Group="Vitamins" Name="Total vitamin B6 " Quantity="0.127"></Nutrition>
    <Nutrition Group="Vitamins" Name="Total vitamin D" Quantity="0.3"></Nutrition>
    <Nutrition Group="Vitamins" Name="Total vitamin E " Quantity="2.1"></Nutrition>
    <Nutrition Group="Vitamins" Name="Vitamin B1 " Quantity="0.1"></Nutrition>
    <Nutrition Group="Vitamins" Name="Vitamin B12 " Quantity="0.59"></Nutrition>
    <Nutrition Group="Vitamins" Name="Vitamin B2" Quantity="0.16"></Nutrition>
    <Nutrition Group="Vitamins" Name="Vitamin C" Quantity="10"></Nutrition>
</Nutritions>

We will use LINQ to read the Xml file and get the information about each nutrition. If you want to know about how to use LINQ for reading or writing Xml documents, take a look at this article. I also create a class called Nutrition which has three properties - Group, Name, Quantity. Now what we need is to extract a list of Nutritions from the Xml and set it as source of our DataGrid. The ItemsSource property is used for that purpose. Here is the code:

private void LoadData()
{
    XDocument nutritionsDoc = XDocument.Load( "Nutritions.xml" );
    List<Nutrition> data = ( from nutrition in nutritionsDoc.Descendants( "Nutrition" )
                             select new Nutrition
                             {
                                 Group = nutrition.Attribute( "Group" ).Value,
                                 Name = nutrition.Attribute( "Name" ).Value,
                                 Quantity = nutrition.Attribute( "Quantity" ).Value
                             } ).ToList();
 
    Foods.ItemsSource = data;
}

And here is the result:

 

Manually defining the columns

When we know exactly what properties the object has or when we want not every property to be shown as column, we can manually define the columns and the bindings. In this case we need Text columns, but in the next article we'll see the other types of columns.

Update: The DisplayMemberBinding proeprty is renamed to Binding in the RTW release.

Xaml

<my:DataGrid x:Name="Foods">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Binding="{Binding Group}" Header="Group"></my:DataGridTextColumn>
        <my:DataGridTextColumn Binding="{Binding Name}" Header="Name"></my:DataGridTextColumn>
        <my:DataGridTextColumn Binding="{Binding Quantity}" Header="Quantity"></my:DataGridTextColumn>
    </my:DataGrid.Columns>
</my:DataGrid>

C#

DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.Header = "Group";
textColumn1.Binding = new Binding( "Group" );
Foods.Columns.Add( textColumn1 );
 
DataGridTextColumn textColumn2 = new DataGridTextColumn();
textColumn2.Header = "Name";
textColumn2.Binding = new Binding( "Name" );
Foods.Columns.Add( textColumn2 );
 
DataGridTextColumn textColumn3 = new DataGridTextColumn();
textColumn3.Header = "Quantity";
textColumn3.Binding = new Binding( "Quantity" );
Foods.Columns.Add( textColumn3 );

And finally some Silverlight:

As you can see by default we have selection and sorting by columns functionality in the grid, but these are things that we'll take a much closer look soon.

Summary

Now we know how to create a DataGrid control, how to bind some data to it and how to define it's columns. The next time we're going to extend this example by adding some styles and templates and other cool things. So stay tuned!

Share


Comments

Comments RSS RSS
  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Frank on Sep 13, 2008 13:28

    Great .. nice job .. very easy to understand

     

    how do you change, with code behind, one of the elements in the datagrid .. ie the quantity for Calcium

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Enrai on Sep 15, 2008 07:48

    The editing of the contents of the DataGrid will surely be a theme for one of the next articles. If you're using Text columns in your DataGrid by double-clicking on a cell you go in edit mode. If you're using a Template column you must define a CellEditingTemplate as well and again with double-click you go in edit mode. After you've done editing just press enter or change the selection and your changes will be submitted. You can also create an event handler for the ComittingEdit event of the DataGrid and use the event arguments for additional actions. There a few more events that concern the editing but I'll explain them in the upcomming articles. Hope that will do the work for you.

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Jitendra Kumar on Nov 10, 2008 01:03

    I am not getting XDocument class in silverlight 2.Please help

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Enrai on Nov 11, 2008 02:36

    To use the XDocument and the LINQ to XML syntax you have to add a reference to the System.Xml.Linq.dll and use the System.Linq namespace. That's all. You can read more about that here - Using LINQ to XML in Silverlight 2.

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Dan on Nov 13, 2008 14:59

    How did you get the empty column to the left of the "Group" column with the arrow when the row is selected in your example in the "Adding some data" section?

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Enrai on Nov 13, 2008 23:42

    Hi, Dan

    That isn't an empty column, these are the row headers. In the Silverlight sample I have hidden them, but when I took the screenshot they were visible. Sorry if that has confused you. :)

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by kapil on Dec 17, 2008 03:39

    do we have any support for Column Grouping in the datagrid?

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Enrai on Dec 20, 2008 06:09

    Hi, kapil

    There is no default support for ColumnGrouping in the DataGrid. Although there are some custom DataGrids for Silverlight that provide such functionality - the agDataGrid by DevExpress for example. It's free and comes with source code, so you can take a look at it and see how this is accomplished.

    I think it can be done by manipulating the ColumnHeader template. When I find some spare time I'll give it a try.

    This topic in the silverlight.net forum could also be helpful to you.

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by rose on Jan 28, 2009 00:31

    hi...

    can anyone explain in detail where write these codes...ie in nutriton.cs,page,xaml.cs

    plllzz...explain in detail....

     

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Ramprasad on Jan 31, 2009 08:06

    Frozen Columns in Silverlight DataGrid..
    http://dotnetdreamer.wordpress.com/2009/01/31/silverlight-2-datagrid-frozen-columns/

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Keerthi on Mar 17, 2009 05:07
    Hi,

    very nice.. but all the data are displayed twice in the grid..

    anyone pls help me out..
  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by W.Meints on Mar 30, 2009 07:14
    Great article and a great control. I've tried the one from infragistics, but they upgraded to silverlight 3.0 so that one is out the window for me. I am keeping an eye out for the next articles about this one.
  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by dbs on Apr 23, 2009 21:23
    Excelent!
  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Krishna on May 13, 2009 01:40
    Hi,

     I see an empty column on the right side, in your example after quantity there is an empty column. why does this empty column appear and can you please tell me how to remove it.

     Thanks

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Roshni on Dec 05, 2009 08:15

    hi,

        I am not getting commitcelledit Event in Data:DataGrid.

    Thank You.

  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by ram on Mar 08, 2010 14:27
    its amazing ... simply superb... i dont have words to speak .... thank you so much
  • RE: Introduction to the DataGrid control in Silverlight 2  

    posted by Soonam on Apr 01, 2010 13:38

    To remove the empty column in the Right side , stretch all the columns

    ColumnWidth="*"

  • Read From XML into Chat Controle Using LINQ  

    posted by suri on May 18, 2010 14:51
    How to retrieve the Data from xml into chart controls using LINQ in Silver light Applications.

Add Comment

 
 

   
  
  
   
Please add 8 and 6 and type the answer here:

Join the free SilverlightShow webcast 'Running Silverlight Outside the Browser and with Elevated Trust'. Sept 7th, 8 am - 9 am PDT.
In this live session Chris Anderson will cover configuring and debugging OOB mode, toast notifications, elevated trust, direct file access and much more.
Learn more | Register | See more webinars (hide this)