Effective Data Representation in Silverlight 4.0 using TargetNullValue, StringFormat and FallbackValue

Posted by: Mahesh Sabnis , on 8/1/2010, in Category Silverlight 2, 3, 4 and 5
Views: 26123
Abstract: A common issue that I hear from my clients regarding data representation in Silverlight ItemsControls is that while fetching data from service and displaying in a DataGrid, some data values (especially string) are sometimes Null and also some numeric values need to be represented in a currency format.
A common issue that I hear from my clients regarding data representation in Silverlight ItemsControls is that while fetching data from service and displaying in a DataGrid, some data values (especially string) are sometimes Null and also some numeric values need to be represented in a currency format.
Silverlight 4.0 Binding class, provides mechanism to handle the data representation easiness using TargetNullValue, StringFormat and FallBackValue properties.     
·         TargetNullValue: Used to represent value in the UI when the source value is Null.
·         StringFormat: Used to specify a specific format for the data when it is to be represented in UI. E.g. Current ‘C’ etc.
·         FallBackValue: If the binding source path is not found then this is used to represent value in UI.
In this article, for simplicity sake I am not using any Service but instead I have created a simple class ‘clsEmployee’ for data consumption and to be used as a source.
 
Step 1: Open VS2010 and create a Sliverlight Application targeting version 4.0. Name this as ‘SILV_TargetNullValues’.
Step 2: To the Silverlight project, add a new class file and name this as ‘DataAccessClasses.cs’, write following two classes in it:
C#
 
namespace SILV_TargetNullValues
{
    public class clsEmployee
    {
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public string DeptName { get; set; }
        public string Designation { get; set; }
        public decimal? Salary { get; set; }
    }
 
    public class EmployeeCollection : ObservableCollection<clsEmployee>
    {
        public EmployeeCollection()
        {
            Add(new clsEmployee() { EmpNo = 101, EmpName = "Emp_1", DeptName = "IT", Designation = "Manager", Salary = 78000 });
            Add(new clsEmployee() { EmpNo = 102, EmpName = "Emp_2", DeptName = "IT", Designation = "Engineer", Salary = 88000 });
            Add(new clsEmployee() { EmpNo = 103, EmpName = "Emp_3", DeptName = "ACCT", Designation = "Manager" });
            Add(new clsEmployee() { EmpNo = 104, EmpName = "Emp_4", DeptName = "ACCT", Designation = "Clerk", Salary = 68000 });
            Add(new clsEmployee() { EmpNo = 105, EmpName = "Emp_5", Designation = "Manager", Salary = 38000 });
            Add(new clsEmployee() { EmpNo = 106, EmpName = "Emp_6", DeptName = "HRD", Salary = 88000 });
            Add(new clsEmployee() { EmpNo = 107, EmpName = "Emp_7", DeptName = "HRD", Designation = "HEAD", Salary = 98000 });
            Add(new clsEmployee() { EmpNo = 108, EmpName = "Emp_8", Designation = "Manager", Salary = 48000 });
            Add(new clsEmployee() { EmpNo = 109, EmpName = "Emp_9", DeptName = "IT", Salary = 58000 });
            Add(new clsEmployee() { EmpNo = 110, EmpName = "Emp_10", Designation = "Manager", Salary = 78000 });
        }
    }
}
 
VB.NET
 
Namespace SILV_TargetNullValues
      Public Class clsEmployee
            Public Property EmpNo() As Integer
            Public Property EmpName() As String
            Public Property DeptName() As String
            Public Property Designation() As String
            Public Property Salary() As Decimal?
      End Class
 
      Public Class EmployeeCollection
            Inherits ObservableCollection(Of clsEmployee)
            Public Sub New()
                  Add(New clsEmployee() With {.EmpNo = 101, .EmpName = "Emp_1", .DeptName = "IT", .Designation = "Manager", .Salary = 78000})
                  Add(New clsEmployee() With {.EmpNo = 102, .EmpName = "Emp_2", .DeptName = "IT", .Designation = "Engineer", .Salary = 88000})
                  Add(New clsEmployee() With {.EmpNo = 103, .EmpName = "Emp_3", .DeptName = "ACCT", .Designation = "Manager"})
                  Add(New clsEmployee() With {.EmpNo = 104, .EmpName = "Emp_4", .DeptName = "ACCT", .Designation = "Clerk", .Salary = 68000})
                  Add(New clsEmployee() With {.EmpNo = 105, .EmpName = "Emp_5", .Designation = "Manager", .Salary = 38000})
                  Add(New clsEmployee() With {.EmpNo = 106, .EmpName = "Emp_6", .DeptName = "HRD", .Salary = 88000})
                  Add(New clsEmployee() With {.EmpNo = 107, .EmpName = "Emp_7", .DeptName = "HRD", .Designation = "HEAD", .Salary = 98000})
                  Add(New clsEmployee() With {.EmpNo = 108, .EmpName = "Emp_8", .Designation = "Manager", .Salary = 48000})
                  Add(New clsEmployee() With {.EmpNo = 109, .EmpName = "Emp_9", .DeptName = "IT", .Salary = 58000})
                  Add(New clsEmployee() With {.EmpNo = 110, .EmpName = "Emp_10", .Designation = "Manager", .Salary = 78000})
            End Sub
      End Class
End Namespace
 
The above two classes represent entity and collection class. In the EmployeeCollection class constructor, values are added into ObservableCollection. If you carefully look at the code, you will find that some clsEmployee objects have ‘DeptName’, ‘Designation’ and ‘Salary’ missing.
Step 3: On MainPage.xaml, drag and drop a TextBlock and DataGrid control. The Xaml will be as shown below:
<UserControl x:Class="SILV_TargetNullValues.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:src="clr-namespace:SILV_TargetNullValues"        
    mc:Ignorable="d"
    d:DesignHeight="532" d:DesignWidth="868"
             xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
 
    <UserControl.Resources>
        <src:EmployeeCollection x:Key="EmpCol"></src:EmployeeCollection>
    </UserControl.Resources>
        <Grid x:Name="LayoutRoot" Background="White" Width="750" Height="371"
           DataContext="{Binding Source={StaticResource EmpCol}}">
        <TextBlock Height="41" HorizontalAlignment="Left" Margin="80,12,0,0"
                   Name="textBlock1" Text="Employee Information System"
                   VerticalAlignment="Top" Width="452" FontWeight="ExtraBold"
                   FontSize="25" TextAlignment="Center">
        </TextBlock>
 
    
            <sdk:DataGrid AutoGenerateColumns="False" Height="277" HorizontalAlignment="Left"
                      Margin="22,62,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="707"
                       ItemsSource="{Binding}">
 
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Width="100" Header="EmpNo" Binding="{Binding EmpNo}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="140" Header="EmpName" Binding="{Binding EmpName}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="140" Header="DeptName" Binding="{Binding DeptName}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="120" Header="Designation" Binding="{Binding Designation}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="100" Header="Salary" Binding="{Binding Salary}"></sdk:DataGridTextColumn>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
    </Grid>
</UserControl>
 
The above Xaml code represents that the EmployeeCollection class is bound with the DataGrid.
Note: The EmployeeCollection instance is created using UserControl Resources, and using DataContext property of Grid Control.
Step 4: Run the project, the following output will be displayed:
EmpInfoSystemuhyc
If you see the above result, all Red marked rectangles represents records with some values missing. This type of display is not acceptable in a real world application development scenario. Also ‘Salary’ must be represented in a valid currency format. 
To handle such a requirement in Line-of-Business (LOB) applications with Silverlight, version 4.0 has introduced new properties in binding class as I explained in the beginning of this article i.e. TargetNullValue and StringFormat.
Using TargetNullValue and StringFormat
 
Step 5: To display data accurately, make the following changes in the DataGrid columns binding.
<sdk:DataGrid AutoGenerateColumns="False" Height="277" HorizontalAlignment="Left"
                      Margin="22,62,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="707"
                       ItemsSource="{Binding}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Width="100" Header="EmpNo" Binding="{Binding EmpNo}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="140" Header="EmpName" Binding="{Binding EmpName}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="140" Header="DeptName" Binding="{Binding DeptName,TargetNullValue='Not Specified'}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="120" Header="Designation" Binding="{Binding Designation,TargetNullValue='Not Specified'}"></sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Width="100" Header="Salary" Binding="{Binding Salary,TargetNullValue='Not Specified',StringFormat=C}"></sdk:DataGridTextColumn>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
 
Now if you carefully look at the above new xaml, you will find that TargetNullValue is used for ‘Designation’ and ‘DeptName’ properties. Since ‘Salary’ must be currency, StringFormat is used for data representation. If ‘Designation’ and ‘DeptName’ is Null in some records then ‘Not Specified’ string will be displayed and the ‘Salary’ will have currency as ‘$’.
Step 6: Run the application and the following result will be displayed:
EmpInfoSystemuhyc_1
Note: I have declared ‘Salary’ property as Nullable Type. Otherwise you may get ‘0’ (Zero) for the salary for some records wherever it is not specified in source.
 
Using FallBackValue
 
Sometimes, you may need to bind some additional property to the UI control although it is not present in Source or might have been removed from the source, without notifying the UI. Previously Silverlight would not allow us to bind the property which is not present in the source. So to handle such a scenario, the Binding class has provided a property called ‘FallbackValue’ using which even if the property is missing from the source, the alternate fallback can be displayed in UI without crashing it.
Step 7: To make use of ‘FallbackValue’, add a new column in DataGrid as below,:
<sdk:DataGridTextColumn Width="100" Header="Experience" Binding="{Binding Experience,FallbackValue='Not Available'}"></sdk:DataGridTextColumn>
 
Step 8: Run the application and the following result will be displayed:
EmpInfoSystemuhyc_2
The last column Experience is not present in ‘clsEmployee’ class and hence it is not available into ‘EmployeeCollection’, so it shows ‘Not Available’ for all rows.
Conclusion: Silverlight 4.0 has provided an easy mechanism for handling Data Representation using ‘TargetNullValue’, ‘StringFormat’ and ‘FallbackValue’ properties of Binding class to handle scenarios when records as well as source is changing with its values, formats and properties.
The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Vikram Pendse [ Microsoft Silverlight MVP & Insider ] on Tuesday, August 10, 2010 3:12 AM
Nice Article and useful in Line Of Business scenarios.

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook