Bind Silverlight Grid view with WCF Service
Posted by Viral Sarvaiya on September 17, 2010
Hello friends….
Here I demonstrate how to bind the grid view of the Silverlight with WCF Service.
You already know what is the Silverlight and WCF. My one post that demonstrate the use of the WCF Service with Silverlight, for more info about that check http://viralsarvaiya.wordpress.com/2010/08/26/use-of-wcf-service-in-silverlight/
Setp 1 : Create New Silverlight Project( here I give name of the project is “SilverlightGridTest”)
In the Visual Studio 2008 or 2010, file menu -> New -> project.
Select Silverlight application, give name as SilverlightGridTest and open the project.
Then check the checkbox true of the host the Silverlight application in web site.
Now you have 2 project in the solution.
Step 2: Database information
CREATE TABLE person ( Name VARCHAR(256), Phone VARCHAR(50), City VARCHAR(50) )
make one procedure named “GetAllPersonInfo” and write the following Statement in the procedure
Select *from person order by name;
Step 3: Create WCF Service
Right click to SilverlightGridTest.web project, select add -> new item.
Choose Silverlight in left panel and choose Silverlight-enable WCF Service. Then give name “DataService.svc”
So Service has been added to project.
Here we have interface IDataService.cs and DataService will implements that so in our IDataService.cs code is as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace SilverlightGridTest.Web
{
[ServiceContract]
public interface IDataService
{
[OperationContract]
PersonDetails GetPersonDetails();
}
[DataContract]
public class PersonDetails
{
List<Personinfo> _PersonList = new List<Personinfo>();
[DataMember]
public List<Personinfo> PersonIndex
{
get { return _PersonList; }
set { _PersonList = value; }
}
}
[DataContract]
public class Personinfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Phone { get; set; }
[DataMember]
public string City { get; set; }
}
}
In the “DataService.svc.cs” file write the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
namespace SilverlightGridTest.Web
{
public class DataService : IDataService
{
public PersonDetails GetPersonDetails()
{
DatabaseHandler dbObj = new DatabaseHandler();
DataTable dataTablePersonInfo = dbObj.GetPersonInfo();
PersonDetails PersonDataMessage = new PersonDetails();
for (int iTagCounter = 0; iTagCounter < dataTablePersonInfo.Rows.Count; iTagCounter++)
{
Personinfo PersonInfo = new Personinfo();
PersonInfo.Name = dataTablePersonInfo.Rows[iTagCounter]["Name"].ToString();
PersonInfo.Phone = dataTablePersonInfo.Rows[iTagCounter]["Phone"].ToString();
PersonInfo.City = dataTablePersonInfo.Rows[iTagCounter]["City"].ToString();
PersonDataMessage.PersonIndex.Add(PersonInfo);
}
return PersonDataMessage;
}
}
}
Now add the new class name “DatabaseHandler.cs” for the operation on the database. Means this function will get the data from the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.ObjectModel;
namespace SilverlightGridTest.Web
{
public class DatabaseHandler
{
private string _gConnectionString = ConfigurationManager.ConnectionStrings["Database"].ToString();
public DataTable GetPersonInfo()
{
SqlConnection sqlConnect = new SqlConnection(_gConnectionString);
sqlConnect.Open();
DataTable dbTbl = new DataTable();
//Get data
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetAllPersonInfo";
cmd.Connection = sqlConnect;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oAdapter = new SqlDataAdapter(cmd);
oAdapter.Fill(dbTbl);
sqlConnect.Close();
return dbTbl;
}
}
}
Step 4: Web.Config Settings
Database Connection string
<connectionStrings> <add connectionString="packet size=4096;server=ServerName;persist security info=False;database=DatabaseName;uid=UserName;pwd=Password;" /> </connectionStrings>
Service Settings
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <bindings> <customBinding> <binding> <binaryMessageEncoding /> <httpTransport /> </binding> </customBinding> </bindings> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> <services> <service behaviorConfiguration="SilverlightGridTest.Web.TestServiceBehavior" name="SilverlightGridTest.Web.DataService"> <endpoint address="" binding="basicHttpBinding" contract="SilverlightGridTest.Web.IDataService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> </system.serviceModel>
Step 5: Add clientaccesspolicy.xml and crossDomain.xml file.
This will complete the coding in the SilverlightGridTest.Web .
Build the application.
Now move to SilverlightGridTest.
Add the service reference and add the service which we develop above.
Step 6: Mainpage.xaml file.
Now in the Mainpage.xaml file put the grid control.
<UserControl x:Class="SilverlightGridTest.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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">
<sdk:DataGrid x:Name="AllPerson" GridLinesVisibility="All" AutoGenerateColumns="False" >
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding Name}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" />
<sdk:DataGridTextColumn Binding="{Binding Phone}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Phone"/>
<sdk:DataGridTextColumn Binding="{Binding City}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="City"/>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</UserControl>
Step 7 : Mainpage.xaml.cs file
Make the object of the service client, coding as follow.
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;
using SilverlightGridTest.DataService;
namespace SilverlightGridTest
{
public partial class MainPage : UserControl
{
public DataServiceClient objDataService;
public MainPage()
{
InitializeComponent();
objDataService = new DataServiceClient();
objDataService.GetPersonDetailsCompleted += new EventHandler<GetPersonDetailsCompletedEventArgs>(objDataService_GetPersonDetailsCompleted);
objDataService.GetPersonDetailsAsync();
}
void objDataService_GetPersonDetailsCompleted(object sender, GetPersonDetailsCompletedEventArgs e)
{
AllPerson.ItemsSource = e.Result.PersonIndex;
}
}
}
Step 8: Run the application.
You will get the data will display in the grid as below
Enjoy coding…..




Tweets that mention Bind Silverlight Grid view with WCF Service « Web Developer Friend -- Topsy.com said
[...] This post was mentioned on Twitter by Larry King, Viral Sarvaiya. Viral Sarvaiya said: Bind Silverlight Grid view with WCF Service – http://viralsarvaiya.wordpress.com/2010/09/17/bind-silverlight-grid-view-with-wcf-service/ [...]
Rushit Shukla said
Hi Viral,
Really Good One.
Keep it Up Dear.
Kind Regards,
Rushit SHukla
(www.AavidTechnologies.com)
viralsarvaiya said
Dear Rushit,
thank you so much for being regular reader of my blog and appreciate me for writing…..
Ramani Sandeep said
good one..
Anil Maurya said
very nice code for starting with databinding.
anil2711 said
very nice desription..keep it up
viralsarvaiya said
Dear Anil,
Thanks for the valuable comment.
Calling a WCF service from Javascript « Web Developer Friend – Viral Sarvaiya said
[...] http://viralsarvaiya.wordpress.com/2010/09/17/bind-silverlight-grid-view-with-wcf-service/ [...]
Calling a WCF service from Javascript « Web Developer Friend – Viral Sarvaiya said
[...] Posts Difference between ExecuteQuery And Execute NonQueryGridview – insert, update, deleteBind Silverlight Grid view with WCF ServiceUse of WCF Service in SilverlightSQL Server: Return Multiple Values from a FunctionBackground Image [...]
societe offshor said
Hi nice posting. I really agree the majority of these ideas
ranjithkumar said
How can i bind data for dynamic columns..i.e autogenerate =true means what can i do…
viralsarvaiya said
Yes ranjithkumar, You can do that.
pegazuss said
Hi!
Your code is very good.I looking for some idea how can i do,that grid refres auto when somthing change in the databae,wich attached the grid.So,i dont want to put timer or something like that the code to refresh the page.Can you help me?