Sunday, October 16, 2011

Silverlight - Paging in DataGrid in Silverlight 4

In this article i will show you how to bind dynamic data to the DataGrid and how will implement data paging in DataGrid in Silverlight 4.


Step 1
Download Northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en


Step 2
Attach a Northwind database into MS-SQL server.



Step 3

Download Silverlight 4 tools from the following link

Download Silverlight 4 toolkit from the following link
http://silverlight.codeplex.com/



Note : Select only April 2010 Toolkit Silverlight 4


Step 4
Create a Silverlight Application and give the solution name as SolSilverlight_DataGrid_DataPager.




Click on image for better view


Note: Select Web Project Type as ASP.NET Web site.


Step 5
In MainPage.xaml page, drag and drop DataGrid and DataPager in Grid and add respective DatagridTextColumns in DataGrid for binding data,it is look like this




Click on image for better view


<Grid x:Name="LayoutRoot" Background="White">
  <Grid.RowDefinitions>
   <RowDefinition Height="262*" />
   <RowDefinition Height="58*" />
  </Grid.RowDefinitions>
  <sdk:DataGrid x:Name="DgEmployee" Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="All" ItemsSource="{Binding}" >
   <sdk:DataGrid.Columns>
    <sdk:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}"/>
    <sdk:DataGridTextColumn Header="LastName" Binding="{Binding LastName}"/>
    <sdk:DataGridTextColumn Header="BirthDate" Binding="{Binding BirthDate}"/>
    <sdk:DataGridTextColumn Header="City" Binding="{Binding City}"/>
   </sdk:DataGrid.Columns>
  </sdk:DataGrid>
  
  <sdk:DataPager x:Name="DpEmployee" Grid.Row="1" Grid.Column="0" VerticalAlignment="Top" DisplayMode="FirstLastPreviousNextNumeric"  PageSize="3"/>
 </Grid>


Click on image for better view


Now Design part done.let's move to the Code behind part.


Step 6
Select a ASP.net Web Application (SolSilverlight_DataGrid_DataPager.WebAdd app_code folder in the solution and add a new folder inside the app_code folder and give folder name as ORD,it is look like this




Click on image for better view


Step 7
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,selectLINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this




Click on image for better view


Step 8
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this




Click on image for better view




Click on image for better view


Visual stdio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.


Step 9

Create a Employee object.
In this example we have to work with employees table of the Northwind database,create a employee object that will use LINQ to SQL to map to this table.go to the server explorer,select northwind database,go to the tables and select Employees table,it is look like this


Click on image for better view


Drag and drop Employee table from Server explorer onto the design surface of the O/R Designer,it is look like this




Click on image for better view


Step 10
Select a ASP.net Web application (SolSilverlight_DataGrid_DataPager.Web) and add WCF Service,right click on solution,select Add New Item,select WCF Service from installed Visual Studio templates and name it EmployeeService.svc and click on add button.,it is look like this


It will add two .cs (named IEmployeeService.cs and EmployeeService.cs)




Click on image for better view


Step 11
Now we will make some modification to the OperationContract.Remove default DoWork method from the IEmployeeService interface.Add a new Method named as GetEmployeeData,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmployeeService" in both code and config file together.
[ServiceContract]
public interface IEmployeeService
{
    [OperationContract]
    List<ord.employee> GetEmployeeData();
}

Step 12
Implement IEmployeeService interface in EmployeeService class, retriving an employee data from database,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ORD;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EmployeeService" in code, svc and config file together.
public class EmployeeService : IEmployeeService
{
    /// 
    /// Get Employee Data From Northwind Database
    /// 
    /// List
    public List<Employee> GetEmployeeData()
    {
        try
        {
            ORD.NorthwindDCDataContext DC = new NorthwindDCDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.Trim());

            var Query = from Q in DC.Employees
                        select new ORD.Employee
                        {
                            FirstName = Q.FirstName,
                            LastName = Q.LastName,
                            BirthDate =Q.BirthDate,
                            City = Q.City
                        };

            return Query.ToList<ORD.Employee>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }
}


Step 13
Add a Service Reference of  WCF Service in silverlight application(SolSilverlight_DataGrid_DataPager).Right click the Silverlight project and add a Service reference,it is look like this




Click on image for better view


Step 14
Add a WCF service in the silverlight application.Add Service Reference dialog box will open and click on Discover button and give the namesapace name as EmployeeServiceReference.




Click on image for better view


Step 15
Get List of Employee Data from WCF Service and Bind to the DataGrid then Bind Item Source of the DataGrid to the DataPager control,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SolSilverlight_DataGrid_DataPager
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            try
            {
                // Call Employee Service Method in Constructor
                CallEmployeeWCFService();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        #region Methods

        private void CallEmployeeWCFService()
        {
            try
            {
                // Call WCF Service
                EmployeeServiceReference.EmployeeServiceClient EmployeeServiceClientObj = new EmployeeServiceReference.EmployeeServiceClient();

                // Wire up the Async Completed  handler
               EmployeeServiceClientObj.GetEmployeeDataCompleted += new EventHandler<EmployeeServiceReference.GetEmployeeDataCompletedEventArgs>(EmployeeServiceClientObj_GetEmployeeDataCompleted);

                // Call WCF Method 
                EmployeeServiceClientObj.GetEmployeeDataAsync();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        void EmployeeServiceClientObj_GetEmployeeDataCompleted(object sender, EmployeeServiceReference.GetEmployeeDataCompletedEventArgs e)
        {
            try
            {
                // Wrap list Employee to paged Collection view then bind to data grid
                DgEmployee.DataContext = new System.Windows.Data.PagedCollectionView(e.Result);

                // Bind item source of Employee DataGrid to the Data Pager Control
                DpEmployee.Source = DgEmployee.ItemsSource;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }

        #endregion

    }

    

}


Run the Project.

Output




Click on image for better view


Full XAML Code
<UserControl
 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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="SolSilverlight_DataGrid_DataPager.MainPage"
 mc:Ignorable="d"
 d:DesignHeight="320" d:DesignWidth="630">

 <Grid x:Name="LayoutRoot" Background="White">
  <Grid.RowDefinitions>
   <RowDefinition Height="262*" />
   <RowDefinition Height="58*" />
  </Grid.RowDefinitions>
  <sdk:DataGrid x:Name="DgEmployee" Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="All" ItemsSource="{Binding}" >
   <sdk:DataGrid.Columns>
    <sdk:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}"/>
    <sdk:DataGridTextColumn Header="LastName" Binding="{Binding LastName}"/>
    <sdk:DataGridTextColumn Header="BirthDate" Binding="{Binding BirthDate}"/>
    <sdk:DataGridTextColumn Header="City" Binding="{Binding City}"/>
   </sdk:DataGrid.Columns>
  </sdk:DataGrid>
  
  <sdk:DataPager x:Name="DpEmployee" Grid.Row="1" Grid.Column="0" VerticalAlignment="Top" DisplayMode="FirstLastPreviousNextNumeric"  PageSize="3"/>
 </Grid>
</UserControl>


Download
Download Source Code

4 comments:

  1. ... hay put some : MVVM pattern examples, used in silverlight5.0 ...

    ReplyDelete
    Replies
    1. Sure Brother...but now i am busy in project.i will put some interesting silverlight 5.0 example..

      don't worry about that......

      Delete
  2. Thank You for sharing your article, This is an interesting & informative blog. It is very useful for the developer like me. Kindly keep blogging. Besides that Wisen has established as Best Corporate Training in Chennai .

    Nowadays JavaScript has tons of job opportunities on various vertical industry. Know more about JavaScript Framework Training visit Corporate Training Companies in India.

    This post gives me detailed information about the technology. corporate training companies in india

    ReplyDelete
  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete