Populate a GridView from web service
DataSetWebService.asmx
<%@ WebService Language="C#" Class="DataSetWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class DataSetWebService : System.Web.Services.WebService{
[WebMethod]
public DataSet GetProducts(){
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
SqlDataAdapter myAdapter;
DataSet productDataSet;
string commandString = "Select Top 9 ProductID, ProductName, UnitPrice From Products";
myAdapter = new SqlDataAdapter(commandString, conn);
productDataSet = new DataSet();
myAdapter.Fill(productDataSet);
return productDataSet;
}
}
WebServiceReturnDataSet.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
ProductsService.DataSetWebService ws = new ProductsService.DataSetWebService();
GridView1.DataSource = ws.GetProducts();
GridView1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to populate GridView from web service in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Crimson; font-style:italic;">Web Service Example: Using Web Service and DataSet</h2>
<hr width="500" align="left" color="Salmon" />
<asp:GridView
ID="GridView1"
runat="server"
ForeColor="DodgerBlue"
BackColor="AliceBlue"
Font-Bold="false"
Font-Italic="true"
BorderColor="CornflowerBlue"
Font-Names="Comic Sans MS"
>
<HeaderStyle
ForeColor="Snow"
BackColor="DodgerBlue"
Font-Bold="true"
/>
</asp:GridView>
<br />
<asp:Button
ID="Button1"
runat="server"
Font-Bold="true"
ForeColor="SaddleBrown"
Text="Consume Web Service and Populate GridView"
OnClick="Button1_Click"
Height="45"
/>
</div>
</form>
</body>
</html>

