Fetch data from a WCF Data Service and displaying it on Windows Forms DataGridView component

Posted: (EET/GMT+2)

 

The OData protocol and WCF (Windows Communication Foundation) Data Services technology are an exciting combination for many .NET developers. However, most examples I've seen on the Internet about these technologies simply talk about Silverlight. This is cool, true, but then again, you might have older applications using WinForms (Windows Forms) technologies that could still benefit from these technologies. The purpose of this blog post is to change the situation, and provide you quick step-by-step instructions on how to get started.

Firstly, start a new WinForms project. I'm assuming you are using Visual Studio 2008 or 2010 or later here. With the OData endpoint URL copied to the clipboard (try http://services.odata.org/Northwind/Northwind.svc/ for a quick test), add a Service Reference to your project, and let Visual Studio know your endpoint URL. The result should be an entity (object) model that resembles the data model published by OData.

Now, open a form in Visual Studio. You might be tempted to drag just an empty DataGridView component, write a LINQ query against the entity model, and assign the query results to DataSource property of the grid. Well, it compiles, but doesn't work as there are no columns to display, and thus no data shown.

Instead, let Visual Studio create the columns for you. Open the Data Sources window in Visual Studio, and you should see your data model. Drag a suitable table (such as the Customers table in the above URL) to your form, and Visual Studio will create a nice data grid for you, with associated components.

Then, add for instance a button to the form, and to the button click event handler, write your favorite LINQ query using the ServiceReference1.NorthwindEntities object. Once you have the results in a C# variable (using the var keyword is convenient), simply assign the results to the DataGridView's DataSource property.

There you have it!