The Silverlight DataGrid is a very commonly used control for displaying huge amounts of data. Similarly to save screen space and display Master-Details scenarios, a Nested DataGrid is recommended.
In Silverlight, the DataGrid provides ‘RowDetailsTemplate’, using ‘additional details’ of a DataGrid row can be viewed. DataGrid RowDetailsTemplate accepts DataTemplate as its input and in the DataTemplate, we can put any other control like a DataTemplate for ItemsControls. In this article, I have shown a demonstration for the same:
Step 1: Open VS2010 and create a Silverlight application project. Name it as ‘SL4_Master_Details_DataGrid’. In this project, add a class file and name it as DataClasses.cs. Write the following code in it:
The above class file defines classes for Order and Customer information. It also defines a class for storing Customer-Order details using CustomerCollection class. In a realistic scenario, you can make use of a WCF DataService or WCF Service returning Customer-Order details using a join query.
Now the challenge over here is to display this related data (nested data). In a typical UI, we could have created a ListBox with Customer Details and a DataGrid for displaying Order details. However this could utilize a lot of screen space and we would need to manage two separate controls – first we’d need to write code for data selection in the ListBox and then code to display child records in DataGrid, using some filter on the collection. But in Silverlight, using the RowDetailsTemplate, we can easily have a nested child DataGrid for each DataGrid row, for the parent.
Step 2: In the MainPage.Xaml write the following Xaml code:
The above xaml code defines an instance of the CustomerCollection class in the resources of the UserControl. This instance is further bound with the Grid named LayoutRoot. Here are the important things to observe about the DataGrid, in the XAML code shown above:
- The HeaderVisibility property of the DataGrid is set to ‘All’. This will display DataGrid Row headers along with column headers. This helps the user to select the row for which the details are to be viewed.
- In the RowDetailsTemplate of the parent DataGrid, the child DataGrid is added, which is bound with the ‘Orders’ collection from the source.
Step 3: Run the application and click on the header of the row (extreme left). The following result will be displayed:
As seen above, the order details are displayed in the child DataGrid for the CustomerId 101.
Where can a Nested DataGrid be useful?
One practical example where this can be useful is if you are developing a Hospital Management System where the UI contains Doctor Details in a Tabular UI format. Now the end-user demands that the details of all patients for a doctor must be displayed immediately in Tabular format, whenever a doctor is selected in the Grid.
Download the source code
Will you give this article a +1 ? Thanks in advance