Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

January 22, 2011

Populating a DataGrid in a Silverlight Application

Filed under: C#,Silverlight,VB.NET @ 4:36 pm

One of the common requirements of a line of business application is to present data. This post demonstrates the basics of how to populate a DataGrid from a business object. This post is a "stepping stone" to the ultimate goal of populating the DataGrid using MVVM, which is a later post in this series.

NOTE: This post is part of a series that starts with this prior post. The example in this post uses the application that is built as part of that series.

The basic steps for populating a DataGrid in a Silverlight application are:

1) Drag and drop a DataGrid control from the toolbox onto the desired page.

2) Build/generate the business objects that contains the data for the grid.

3) Bind the business objects to the data grid using the DataGrid’s ItemsSource.

Step 1 is self explanatory. If you are working through the set of blog posts, add the grid to the Students page. Otherwise, add a grid to any page.

Be sure to set the AutoGenerateColumns property to True so it will automatically show your data.

The Silverlight page is called a "View" because it is the user’s view of the application. It is the part of the application that the user sees and interacts with.

Step 2 requires a fundamental decision on how you will get data into your application. The primary choices are:

  • Build an entity class in the Silverlight application that is populated from a WCF service.
  • Generate an entity class in the Silverlight application using WCF RIA services and Entity Framework.
  • Generate an entity class in the Silverlight application using WCF RIA services and your business objects (sometimes called Plain Old CLR Objects or POCOs). See this prior post for more information on using WCF RIA with your business objects.

The details of these approaches is beyond the scope of this post, so this example builds an entity class in the Silverlight application that is populated from code to keep things simple.

Regardless of the approach, the entity class that defines the structure of the data is called the "Model" because it models, or represents, the application’s data.

Add a Models folder to your Silverlight project. In that folder, add a Student class.

In C#:

using System;

namespace InStepSM.SL.Models
{
    public class Student
    {
        public String StudentName { get; set; }
        public int StudentId { get; set; }
        public decimal Project1Score { get; set; }
        public decimal Project2Score { get; set; }
        public decimal Project3Score { get; set; }
    }
}

In VB:

Namespace Models
    Public Class Student
        Public Property StudentName As String
        Public Property StudentId As Integer
        Public Property Project1Score As Decimal
        Public Property Project2Score As Decimal
        Public Property Project3Score As Decimal
    End Class
End Namespace

This class includes a student’s name, Id, and three scores. To keep things simple, the data to populate the class is in the code behind for the xaml file.

Step 3 requires setting the DataGrid’s ItemsSource property to a list of students from the class.

The code behind file for the xaml containing the data grid is shown below:

In C#:

using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Navigation;
using InStepSM.SL.Models;

namespace InStepSM.SL.Views
{
    public partial class Overview : Page
    {
        {
            InitializeComponent();

            dataGrid1.ItemsSource = GetStudents();
        }

        public ObservableCollection<Student> GetStudents()
        {
            var studentList = new ObservableCollection<Student>()
                    {new Student(){StudentName="Frodo Baggins",
                                    Project1Score = 89M,
                                    Project2Score=93M,
                                    Project3Score=88M},
                    new Student(){StudentName="Rosie Cotton",
                                    Project1Score = 97M,
                                    Project2Score=93M,
                                    Project3Score=94M},
                    new Student(){StudentName="Samwise Gamgee",
                                    Project1Score = 83M,
                                    Project2Score=90M,
                                    Project3Score=85M},
                    new Student(){StudentName="Peregrin Took",
                                    Project1Score = 69M,
                                    Project2Score=72M,
                                    Project3Score=75M}};
            return studentList;
        }
    }
}

In VB:

Imports System.Collections.ObjectModel
Imports InStepSM.SL.Models

Partial Public Class Overview
    Inherits Page

    Public Sub New()
        InitializeComponent()

        dataGrid1.ItemsSource = GetStudents()
    End Sub

    Public Function GetStudents() As ObservableCollection(Of Student)
        Dim studentList = New ObservableCollection(Of Student)() From
                {New Student() With {.StudentName = "Frodo Baggins",
                                .Project1Score = 89D,
                                .Project2Score = 93D,
                                .Project3Score = 88D},
                New Student() With {.StudentName = "Rosie Cotton",
                                .Project1Score = 97D,
                                .Project2Score = 93D,
                                .Project3Score = 94D},
                New Student() With {.StudentName = "Samwise Gamgee",
                                .Project1Score = 83D,
                                .Project2Score = 90D,
                                .Project3Score = 85D},
                New Student() With {.StudentName = "Peregrin Took",
                                .Project1Score = 69D,
                                .Project2Score = 72D,
                                .Project3Score = 75D}}
        Return StudentList
    End Function

End Class

The Silverlight designer does not execute the constructor of the code behind, so it does not populate the data or set the ItemsSource. That means that the designer looks like this:

image

Not very helpful. The lack of data in the designer is especially problematic as you try to style or theme the DataGrid. (This issue is handled as the application is moved to an MVVM architecture.)

If you run the application, you will see the results:

image

Use the techniques presented here if you need to bind a set of data to a DataGrid. (Or use the techniques presented in this later post to bind using MVVM.)

Enjoy!

UPDATED 1/25/11: Added information on setting AutoGenerateColumns to True to automatically display the data.

5 Comments

  1.   Peter — January 25, 2011 @ 3:21 am    Reply

    Thanks for this informative article. In terms of getting data into client side, there is another option is to using CSLA business objects with sever data portal.

  2.   Jonathan — January 25, 2011 @ 1:18 pm    Reply

    Just to say all your posts about Silverlight are great, just started learning it and i find your blog very helpful. Also when you add dataGrid from toolbox AutoGenerateColumns property is set to False so you need to set it to True if you want your student data to show (for all who don’t know why their dataGrid is empty).

  3.   DeborahK — January 25, 2011 @ 11:02 pm    Reply

    Hi Jonathan –

    Thanks for pointing out that I missed mentioning the AutoGenerateColumns. I’ll update the instructions above.

  4.   Dhinesh kumar — April 6, 2011 @ 11:08 am    Reply

    Hello Deborah

    Can you please explain how to fill or load the observable collection straight using entity class data objects. As in your posts, the observable collection is loaded with default values. I am trying to update the data grid and its rows using observable collection. I don’t know how to assign the observable collection to data context ( It may be Entity Context using wcf service or Entity framework, or Business objects) as well perform update to database via data contexts. Please help.

    Best Regards
    Dhinesh Kumar

  5.   Bhushan — April 7, 2011 @ 5:18 am    Reply

    Hi, thanks for giving this article in details like enabling the AutoGenerateColumns property to true.

    It helped me solve my problem…

    Thanks a lot

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs