Pages

Wednesday, November 30, 2011

Binding Silverlight DataGrid using Linq to sql

This article explain in the simple way how to bind the silverlight datagrid using linq to sql. I have tried to capture all of the important details and provide a step-by-step example here.

Note, i'm using customer table of the  AdventureWorksLT Database for this project.
We will start creating the project in Visual Studio 2010
    1. Create a new Silverlight application and name the application as “DataGrid”.

    2. Right click on your the web project, then Add->New Item, and choose “LinqToSql”.

    3. Open the Server Explorer, then open the table and drag the table onto the Designer 
        workspace.

    4. The Serialization mode to Unidirectional by right-clicking on the Designer workspace and
         using the Property.

    5. Right click on your web project, then Add->New Item, and choose “WCF Service”.

    6.Open the IService1.cs file and add the GetCustomers method.
 List<Customer> list = db.Customers.ToList<Customer>();
    7. Open the Service1.svc.cs file and implement the GetCustomers method.
public List<Customer> GetCustomers()
{
DataClasses1DataContext db = new DataClasses1DataContext();
List<Customer> list = db.Customers.ToList<Customer>();
return list;
}
    8. Add a reference to the Web Service in the Silverlight project- To do that you need to
        right-click on the references in the Silverlight project and choose the
       'Add Service Reference' item. Then add the Service1.svc.



    9. Create a new DataGrid and Button and Set the DataGrid AutoGenerateColumns
        property as true. < AutoGenerateColumns="True" >

    10. In the button's Click event, create a new instance of the WebService, subscribe to the
          GetCustomerDetails event and call the GetCustomersAsync method.
     private void button1_Click(object sender, RoutedEventArgs e)
        {
       ServiceReference1.
Service1Client webService = new     DataGrid.ServiceReference1.Service1Client();
       webService.GetCustomersCompleted += new
  EventHandler<DataGrid.ServiceReference1.GetCustomersCompletedEventArgs>(GetCustomerDetails);
      webService.GetCustomersAsync();
        }
    11. Finally, in the GetCustomerDetails event handler, bind the DataGrid. Using this code
void GetCustomerDetails(object sender, DataGrid.ServiceReference1.GetCustomersCompletedEventArgs e)
{
this.Customer_Grid.ItemsSource = e.Result;
}
    12. Now run the program and click on display button to display the details.

No comments:

Post a Comment