Silverlight: Data Validations in DataGrid

While developing Silverlight Line-of-Business (LOB), application data validation becomes a very important aspect of UI application development. So if an end-user is using DataGrid for performing Insert or Update operations, then data validations while inserting or updating  should be handled. Silverlight provide the facility of using IDataErrorInfo interface for validation logic. The data model class needs to implement this interface and then the concerned logic for a specific property can be written. In the small code snippet shown below, I have explained this procedure.

Step 1: Create a Silverlight Application and add a class file in it with the following code:

using System.Collections.ObjectModel;
using System.ComponentModel;

public class Employee : INotifyPropertyChanged, 
IDataErrorInfo
{
int _EmpNo;

public int EmpNo
{
get
{
return _EmpNo;
}
set
{
_EmpNo = value;
ChangeValue("EmpNo");
}
}
string _EmpName;

public string EmpName
{
get
{
return _EmpName;
}
set
{
_EmpName = value;
ChangeValue("EmpName");
}
}
int _Salary;

public int Salary
{
get
{
return _Salary;
}
set
{
_Salary = value;
ChangeValue("Salary");
}
}
int _DeptNo;

public int DeptNo
{
get
{
return _DeptNo;
}
set
{
_DeptNo = value;
ChangeValue("DeptNo");
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void ChangeValue(string PropName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, 
new PropertyChangedEventArgs(PropName));
}
}

string err;
public string Error
{
get { return err; }
}

public string this[string columnName]
{
get
{
string msg = null;
if (columnName == "EmpNo")
{
if (EmpNo <= 0 || EmpNo.ToString().Length > 7)
{
msg = "EmpNo must not be Negative " +
"or Length must not be more than 7.";
}
}

if (columnName == "EmpName")
{
if (EmpName.Equals(string.Empty))
{
msg = "EmpName is required";
}
}
if (columnName == "Salary")
{
if (Salary <= 0)
{
msg = "Salary must not be Negative.";
}
}
if (columnName == "DeptNo")
{
if (DeptNo <= 0)
{
msg = "DeptNo must not be Negative.";
}
}

return msg;
}
}
}

Declare an Employee Collection class as shown below:

Silverlight Employee Collection

Carefully observe the Employee class which implements ‘INotifyPropertyChnaged’ and ‘IDataErrorInfo’ interfaces. The first interface is used to raise the PropertyChanged event when the concerned property is changed in UI. The IDataErrorInfo provides string property for returning Error Messages and ‘this’ validation type.
Step 2: Open MainPage.xaml and in the XAML code, instantiate the EmployeeCollection class. Bind it with a  DataGrid. The xaml code is as shown below:

<UserControl x:Class="SL4_Busy_Indicator.MainPage_DataGrid_DataValidation"
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:SL4_Busy_Indicator"         
mc:Ignorable="d"
d:DesignHeight="332" d:DesignWidth="536" 
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<UserControl.Resources>
<src:EmployeeCollection x:Key="EmpDs"></src:EmployeeCollection>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White"
DataContext="{Binding Source={StaticResource EmpDs}}">
<sdk:DataGrid AutoGenerateColumns="False" Height="248" 
HorizontalAlignment="Left" Margin="50,50,0,0" 
Name="dgEmployee" VerticalAlignment="Top" Width="438"
ItemsSource="{Binding}" ColumnWidth="*">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="EmpNo" 
Binding="{Binding EmpNo,Mode=TwoWay,
ValidatesOnDataErrors=True}">                    
</sdk:DataGridTextColumn>
<sdk:DataGridTextColumn Header="EmpName" 
Binding="{Binding EmpName,Mode=TwoWay,
ValidatesOnDataErrors=True}">                    
</sdk:DataGridTextColumn>
<sdk:DataGridTextColumn Header="DeptNo" 
Binding="{Binding DeptNo,Mode=TwoWay,
ValidatesOnDataErrors=True}">                    
</sdk:DataGridTextColumn>
<sdk:DataGridTextColumn Header="Salary" 
Binding="{Binding Salary,Mode=TwoWay,
ValidatesOnDataErrors=True}">                    
</sdk:DataGridTextColumn>
</sdk:DataGrid.Columns>

</sdk:DataGrid>
<TextBlock Height="32" HorizontalAlignment="Left" Margin="25,12,0,0" 
Name="textBlock1" Text="Validate Employee Data" 
VerticalAlignment="Top" Width="484" TextAlignment="Center" 
FontSize="22" />
</Grid>
</UserControl>

The ‘ValidatesOnDataErrors’ property of the Binding class is used to inform the binding engine that it should raise the validation errors specified in the class implementing IDataErrorInfo interface.

Step 3: Run the application and change the value of cells in a row. The result will be as shown below:

Silverlight Data Grid Validation

Will you give this article a +1 ? Thanks in advance


About The Author

Mahesh is having 10 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). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

1 comment:

Anand said...

Keep field Some Value empty in loading grid also Error is showing

How to validate that..