Bind Dataset to Gridview/DataGrid using C# or VB.net :

Dec 22, 2011 By Anil Gaikwad

In this article we will see how to fetch data into dataset and populate that dat into Gridview or Datagrid i.e. binding that dataset to Gridview or Datagrid.

To Bind Dataset to Gridview/DataGrid using C# or VB.net you need to follow following steps:


  • Create a Sqlcommand object and pass name of the stored procedure to it and Add input output parameters with value to the sqlcommand depending on the stored procedure paranmeters
Dim oCommand As SqlCommand oCommand.CommandText = "Name_of_stored_Procedure" oCommand.Parameters.Add(New SqlParameter("@TestParam", Data.SqlDbType.VarChar, 10)).Value = "value"
  • OR you can fetch data by passing a query to sqlcommand object
Dim oCommand As SqlCommand oCommand.CommandText = "Select * from Customers"
  • Then you can execute that Procedure using DataAdapter and fill data into Dataset
Dim adpt As New SqlDataAdapter(oCommand) Dim ds As New DataSet() adpt.Fill(ds)
  • At the end you can bind that dataset to a Gridview or Datagrid
GridView1.DataSource = ds.Tables(0) GridView1.DataBind()

Complete Code


C#.net Example:

SqlConnection oConnection = new SqlConnection("Connection_String"); SqlCommand oCommand = new SqlCommand(); oCommand.Connection = oConnection; oCommand.CommandText = "Name_of_stored_Procedure" oCommand.CommandType = CommandType.StoredProcedure; oCommand.Parameters.Add(New SqlParameter("@TestParam", Data.SqlDbType.VarChar, 10)).Value = "value"; SqlDataAdapter adpt = new SqlDataAdapter(oCommand); DataSet ds = new DataSet(); adpt.Fill(ds); GridView1.DataSource = ds.Tables(0); GridView1.DataBind();

VB.net Example:

Dim oConnection As SqlConnection = New SqlConnection("Connection_String") Dim oCommand As SqlCommand oCommand.Connection = oConnection oCommand.CommandText = "Name_of_stored_Procedure" oCommand.CommandType = CommandType.StoredProcedure oCommand.Parameters.Add(New SqlParameter("@TestParam", Data.SqlDbType.VarChar, 10)).Value = "value" Dim adpt As New SqlDataAdapter(oCommand) Dim ds As New DataSet() adpt.Fill(ds) GridView1.DataSource = ds.Tables(0) GridView1.DataBind()