DataGrid binding using Linq To SQl WPF

By | October 29, 2015

In this article I will discuss how to retrieve the data from a database source and bind to a datagrid in WPF using Linq to SQL. The article is for the beginners who want to learn how to bind the data from database using the Linq To sql (dbml)file as DataContext and ObjectDataProvider in the WPF forms without doing any coding in the code behind file.

Become an Expert in Programming and Web Development.View all courses!


For Add/Edit/Delete of the data, please visit my next article here.
Developing the data driven application using the Linq To SQL is same as using Entity framework in the same way that we don’t have to deal with the database directly. That part is done by the .NET framework using the classes which it create while developing the Linq to SQL relationship.

Following is the step by step by step guide to retrieve the data using Linq To SQL.

  1. I have created a new WPF project for demo as shown in the figure below.Binding DataGrid using Linq To SQL
  2. Now I will add a new item Customer.dbml class as shown below
    Linq To SQL
  3. Once the Customer.dbml class is added to the VS solution. Double click on it and it will open the designer for the class as shown belowLinq To SQl Datagrind binding
  4. After opening the designer, we have to open the server explorer in the visual studio. I am using the Customers table of the northwind database to populate my data grid. Drag and drop the Customers table into the designer of the Customer.dbml. After dropping the Customer table into the designer save the Customer.dbml file.Linq To SQL DataGrid
  5. Now open the Customer.cs file for the same Customer.dbml file by right clicking on it and selecting ViewCode.Include the two namespces System.Linq and System.Collection.Generics and create a new functions named GetAllCustomers() as shown in the code below
  6. After writing the above code, now we will write an ObjectDataProvider in the MainWindow.xaml. ObjectDataProvider is used to create an instance of any class in the Xaml file and call the methods from there.

As soon as we are done with the above coding we can run the application and see that the datagrid is populated with the data from the database as shown in the figure below.

Linq To SQL DataGrid

 

Please find the solution of the article attached here for your reference.

Hope this article has helped you to understand how we can bind the data from a data source using Linq to SQL and ObjectDataProvider in WPF. In my next article I will show how we can update the same data using to the DataBase back.