My Master's Thesis Problems and solutions encountered…


DataGrid Control

The DataGrid property allows you to list large amounts of data within a table. With Silverlight, the grid contains rich user functionality, including automatic resizing, reordering and auto-generating of columns.

This post is only relevant, if you want to hardcode data and insert it into a grid. If you want to get the data from a database, you'll need to do it trough a Web Service. See my post called Accessing Data Through Web Services to learn more about this.

Step 1: You need to create a reference to System.Windows.Controls.Data, by right-clicking on your project >> Add Reference >> .Net >> code>System.Windows.Controls.Data. Then, insert the following xmlns at the top of your .xaml page, where you will be inserting your Grid:


Step 2: Insert the DataGrid into your .xaml page.

Notice the IsReadOnly property:

 <data:DataGrid x:Name="dg" IsReadOnly="True" Margin="10"/>

Step 3: Create a new class by right-clicking on the project >> Add >> Class. Populate the DataGrid by building a class that will be bound to the DataGrid. We define a few properties to bind to, and these represent the columns that the DataGrid will contain.

I called the class Data.cs and inserted the following code:

public class Data
        public string Name { get; set; }
        public int Green { get; set; }
        public int Yellow { get; set; }
        public int Red { get; set; }
        public int NA { get; set; }
        public string Certification { get; set; }


Step 4: In the code-behind for the .xaml page that contains your DataGrid, insert the code shown below.

Notice that the List< Data> on line 5 refers to the class, and the dg in the dg.ItemsSource refers to the name you have given the DataGrid.

public Page()

            List<Data> source = new List<Data>();
            int itemsCount = 15;

            for (int i = 1; i < itemsCount; i++)

                source.Add(new Data()
                    Name = "Company " + i,
                    Green = i + 20 - 7,
                    Yellow = 20 + 7 - i,
                    Red = 0,
                    NA = 0,
                    Certification = "test" + i

            dg.ItemsSource = source;

That's it!

Of course, the loop is just practical for creating rows and content fast. In any other case, just delete the loop and repeat the Source.Add(newData) method as many times as needed.

By following the steps above, you'll get a DataGrid like the one shown below:

Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

1 × = eight

No trackbacks yet.