Silverlight 2.0 DataGrid Demo Application with Formatting of Data

In this post I am going to show you the basic example of Creating the Page with DataBound Silverlight 2.0 DataGrid, and also I will show you how to format the Data Using IValueConverter in DataGrid dynamically.

Create a new project and Select Silverlight Application.

image

Name your application and select Ok, select the options as given in the screen below.

image

Once you select Ok, your solution should look something similar to the one given in the screen below.

clip_image002[9]

Select the DataGrid from the ToolBox and Drag and Drop it on you page, you can also go and Add the DataGrid manually in you XAML code, but if you are doing so then you may also have to add the reference to the assembly and define the custom tag to use for your DataGrid. This is done automatically when you do the Drag and Drop of the control.

clip_image002[11]

Now if you are aware of the Silverlight Layouts then you can format your page and position your DataGrid in more better way as given in the Code below, in the code below I am defining the Rows and Adding the Header for the Page and in the next row I am placing my DataGrid.

Page.xaml

   1: <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="DataGridDemo.Page"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:     xmlns:conv="clr-namespace:DataGridDemo"
   5:     Width="600" Height="300">
   6:     
   7:     <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Center">
   8:         <Grid.RowDefinitions>
   9:             <RowDefinition Height="50"/>
  10:             <RowDefinition Height="*"/>
  11:         </Grid.RowDefinitions>
  12:         <TextBlock Text="List of Player and their details" FontSize="20" Grid.Row="0"></TextBlock>
  13:         <data:DataGrid x:Name="GridPlayer" Grid.Row="1">
  14:             
  15:         </data:DataGrid>
  16:     </Grid>
  17: </UserControl>

 

Now my next task is to create the sample Data to bind the DataGrid, if you already have some data source then you can your that only, or you can use the one as given in the code below. I am creating the Player.cs and PlayerCollection.cs class, which will have to List of Players. Then in GetDemoData in Player.cs I am populating the demo data.

Player.cs

   1: using System;
   2: using System.Net;
   3: using System.Windows;
   4: using System.Windows.Controls;
   5: using System.Windows.Documents;
   6: using System.Windows.Ink;
   7: using System.Windows.Input;
   8: using System.Windows.Media;
   9: using System.Windows.Media.Animation;
  10: using System.Windows.Shapes;
  11:  
  12: namespace DataGridDemo
  13: {
  14:     public class Player
  15:     {
  16:         public string FirstName { get; set; }
  17:         public string LastName { get; set; }
  18:         public string SkillSet { get; set; }
  19:         public DateTime DOB { get; set; }
  20:  
  21:         public static PlayerCollection GetDemoPlayers()
  22:         {
  23:             PlayerCollection players = new PlayerCollection 
  24:             {
  25:                 new Player 
  26:                 { 
  27:                     FirstName = "Brij", 
  28:                     LastName = "Mohan", 
  29:                     SkillSet = "Rugby",
  30:                     DOB=Convert.ToDateTime("08/31/1977")
  31:                 }, 
  32:                 new Player
  33:                 {
  34:                     FirstName="David", 
  35:                     LastName="Osborne", 
  36:                     SkillSet="Cricket",
  37:                     DOB=Convert.ToDateTime("01/11/1976")
  38:                 },
  39:                 new Player
  40:                 {
  41:                     FirstName="Henry", 
  42:                     LastName="Smith", 
  43:                     SkillSet="Chess",
  44:                     DOB=Convert.ToDateTime("11/10/1981")
  45:                 }
  46:             };
  47:  
  48:             return players;
  49:         }
  50:     }
  51:  
  52: }

PlayerCollection.cs

   1: using System;
   2: using System.Net;
   3: using System.Windows;
   4: using System.Windows.Controls;
   5: using System.Windows.Documents;
   6: using System.Windows.Ink;
   7: using System.Windows.Input;
   8: using System.Windows.Media;
   9: using System.Windows.Media.Animation;
  10: using System.Windows.Shapes;
  11: using System.Collections.Generic;
  12:  
  13: namespace DataGridDemo
  14: {
  15:     public class PlayerCollection: List<Player>
  16:     {
  17:  
  18:     }
  19: }

 

Now I have all the data ready to bind the Silverlight DataGrid, so I will modify my Page.xaml.cs as the one given below. In the code below I am just binding the Silverlight DataGrid using the ItemSource property of the DataGrid.

Page.xaml.cs

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Net;
   5: using System.Windows;
   6: using System.Windows.Controls;
   7: using System.Windows.Documents;
   8: using System.Windows.Input;
   9: using System.Windows.Media;
  10: using System.Windows.Media.Animation;
  11: using System.Windows.Shapes;
  12:  
  13: namespace DataGridDemo
  14: {
  15:     public partial class Page : UserControl
  16:     {
  17:         public Page()
  18:         {
  19:             InitializeComponent();
  20:             BindDataGrid();
  21:         }
  22:         private void BindDataGrid()
  23:         { 
  24:             GridPlayer.ItemsSource = Player.GetDemoPlayers();
  25:         }
  26:     }
  27: }

Now you can run the application and can see the output.

image

Now one thing you can notice in the screen below, i.e the DOB column, the dates are not coming what we are expecting and also the column name is also not very Readable, so we need to define the ColumnTemplates and add few more codes to customize our data and have more control on the Desing.

image

To format the DOB column, first I have Created the class, I named it here in my project as DateConverter.cs, and also added the reference to System.Windows.Data

Now all we need to derive the Class from IValueConverter Interface and implement the interface, like the one given below

 

DateConverter.cs

   1: using System;
   2: using System.Net;
   3: using System.Windows;
   4: using System.Windows.Controls;
   5: using System.Windows.Documents;
   6: using System.Windows.Ink;
   7: using System.Windows.Input;
   8: using System.Windows.Media;
   9: using System.Windows.Media.Animation;
  10: using System.Windows.Shapes;
  11: using System.Windows.Data;
  12: using System.Globalization;
  13:  
  14: namespace DataGridDemo
  15: {
  16:     public class DateConverter : IValueConverter
  17:     {
  18:  
  19:         #region IValueConverter Members
  20:  
  21:         /// <summary>
  22:         /// Converts values on their way to the UI for display
  23:         /// </summary>
  24:         /// <param name="value">The value to be formatted</param>
  25:         /// <param name="targetType">The target type of the conversion</param>
  26:         /// <param name="parameter">A format string to be used in the 
  27:         /// formatting of the value</param>
  28:         /// <param name="culture">The culture to use for formatting</param>
  29:         /// <returns>The converted or formatted object</returns>
  30:         public object Convert(object value, Type targetType, object parameter, 
  31:             System.Globalization.CultureInfo culture)
  32:         {
  33:             if (parameter != null)
  34:             {
  35:                 string formatterString = parameter.ToString();
  36:                 if (!string.IsNullOrEmpty(formatterString))
  37:                 {
  38:                     return string.Format(culture, formatterString, value);
  39:                 }
  40:             }
  41:             return value.ToString();
  42:         }
  43:  
  44:         /// <summary>
  45:         /// Converts values on their way back from the UI to the backend.
  46:         /// </summary>
  47:         /// <param name="value">The value to be formatted</param>
  48:         /// <param name="targetType">The target type of the conversion</param>
  49:         /// <param name="parameter">A format string to be used in the 
  50:         /// formatting of the value</param>
  51:         /// <param name="culture">The culture to use for formatting</param>
  52:         /// <returns>The converted or formatted object</returns>
  53:         public object ConvertBack(object value, Type targetType, object parameter, 
  54:             System.Globalization.CultureInfo culture)
  55:         {
  56:             return System.Convert.ToDateTime(value, CultureInfo.CurrentUICulture);
  57:         }
  58:  
  59:         #endregion
  60:     }
  61: }

Next you need to Use template and set the following property in your DataGrid

   1: AutoGenerateColumns="False"

Run the application now, you will not see anything in your default.aspx, because we have set the AutoGenerateColumns as False, so we have to write few bits of code to define our own Column Template for the DataGrid, I personally would prefer using the DataGrid.Column Template, as this gives me more control over the data and the design.

Add the following code inside your DataGrid

   1: <data:DataGrid.Columns>
   2:                 <!--First Name-->
   3:                 <data:DataGridTemplateColumn Header="First Name">
   4:                     <data:DataGridTemplateColumn.CellTemplate>
   5:                         <DataTemplate>
   6:                             <TextBlock Text="{Binding FirstName, Mode=TwoWay}"/>
   7:                         </DataTemplate>
   8:                     </data:DataGridTemplateColumn.CellTemplate>
   9:                 </data:DataGridTemplateColumn>
  10:                 <!--End First Name-->
  11:                 <!--Last Name-->
  12:                 <data:DataGridTemplateColumn Header="Last Name">
  13:                     <data:DataGridTemplateColumn.CellTemplate>
  14:                         <DataTemplate>
  15:                             <TextBlock Text="{Binding LastName, Mode=TwoWay}"/>
  16:                         </DataTemplate>
  17:                     </data:DataGridTemplateColumn.CellTemplate>
  18:                 </data:DataGridTemplateColumn>
  19:                 <!--End Last Name-->
  20:                 <!--SkillSet-->
  21:                 <data:DataGridTemplateColumn Header="Skill Set">
  22:                     <data:DataGridTemplateColumn.CellTemplate>
  23:                         <DataTemplate>
  24:                             <TextBlock Text="{Binding SkillSet, Mode=TwoWay}"/>
  25:                         </DataTemplate>
  26:                     </data:DataGridTemplateColumn.CellTemplate>
  27:                 </data:DataGridTemplateColumn>
  28:                 <!--End SkillSet-->
  29:                 <!--DOB-->
  30:                 <data:DataGridTemplateColumn Header="Date of Birth">
  31:                     <data:DataGridTemplateColumn.CellTemplate>
  32:                         <DataTemplate>
  33:                             <TextBlock Text="{Binding DOB, Mode=TwoWay}"/>
  34:                         </DataTemplate>
  35:                     </data:DataGridTemplateColumn.CellTemplate>
  36:                 </data:DataGridTemplateColumn>
  37:                 <!--End DOB-->
  38:             </data:DataGrid.Columns>

Run the application.

You can see the same output, except the Header text of DOB, you had when you had the AutoGenerateColumns=True,

Now I am going to show how you can use your DateConverter.cs class to format your DateTime, to do so

First you need to import the class which we are going to use to format the DateTime, and also we have to define the tag, this can be done by adding the following code in your UserControl Tag

   1: xmlns:conv="clr-namespace:DataGridDemo"

 

The completed UserControl Tag will look something like this as given below

   1: <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="DataGridDemo.Page"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:     xmlns:conv="clr-namespace:DataGridDemo"
   5:     Width="600" Height="300">

Now add the following code in your XAML code just above your LayoutRoot Grid Layout

   1: <UserControl.Resources>
   2:         <conv:DateConverter x:Key="FormatConverter" />
   3: </UserControl.Resources>

Now you have all the required classes and tag defined for your DateConverter.cs, we have to specify the Column in which we are going to apply this format, as currently we are formatting the DateTime, so we have to apply this for our DOB column, by modifying the following code, as given below

 

   1: <TextBlock Text="{Binding DOB, Mode=TwoWay, Converter={StaticResource FormatConverter}, 
   2: ConverterParameter=\{0:D\}}"/>

 

Now run your application you will get the following output

Final Screen

In the screen above you can notice the Date of Birth date format,

So these are the very basic example I had given here to use the Silverlight 2.0 DataGrid and format the data in the Silverlight 2.0 DataGrid.

You can be more creative and can design the whole new look itself and can get the more control on the data using Silverlight 2.0 DataGrid control.

You can download the source code of the complete solution from here

1 Comment

Comments have been disabled for this content.