In this article I will explain how to bind data in a GridView from a SQL Server database using a WCF Service.
Introduction
In this article first we will create a WCF service to get data from a SQL Server table. Then we will bind the data to a GridView control.
Step 1:
Create a new WCF Service Application
Note: I am using Microsoft Visual Web Developer 2010 Express
Step 2:
Add the following code in IService1.cs:
Step 3:
Add the following code in Service1.svc.cs:
Note: Add your connection string to the Web.config file:
Step 4:
Run the application to open the WCF Test Client:
Copy the path of Service1.svc.
Step 5:
We have created a WCF service to retrieve data from a database. Now we will create an ASP.NET Web Application and add (by dragging) a GridView control to the Default.aspx as below:
Step 6:
- Add a WCF service reference in the project
- Right-click on the Service References in Solution Explorer
- Select Add Service Reference
- Paste the location of Service1.svc in the Address box copied in Step 4
- Click on Go
- Click on OK
Step 7:
Add the following code in Default.aspx.cs:
The final output: