ADO.NET

How to bind a grid using disconnected data access model SqlDataAdapter and DataSet in ASP.Net c#?

How to bind a grid using disconnected data access model SqlDataAdapter and DataSet in ASP.Net c#?, someone asked me to explain?

In this article we will discuss about to bind a grid using disconnected data access model SqlDataAdapter and DataSet in ASP.Net c#.  We are creating instance of SqlDataAdapter  by passing sqlconnectiontext and Connection object and create instance for DataSet then fill the dataset with data.

We will be using ProductDetail table.

Step 1: Create a table using the following script with data:

CREATE TABLEProductDetail 
(
 ProductId int identity primary key,
 ProductName nvarchar(50),
 UnitPrice int
)

INSERT INTOProductDetail VALUES('Lenova',523)
INSERT INTOProductDetail VALUES('Nokia 520',550)
INSERT INTOProductDetail VALUES('Micromax',560)
INSERT INTOProductDetail VALUES('Samsung Galaxy S5',926)
INSERT INTOProductDetail VALUES('Sony',450)

Step 2: Copy and paste the following code.

Default.aspx:

 <table style="border: 1px solid #e2e2e2; font-family: Arial">
        <tr>
            <td style="padding:10px 5px 5px 40px">
               <asp:GridView ID="GridView1" runat="server" ></asp:GridView>
            </td>
        </tr>
   </table>

Default.aspx.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
 
public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string ConnString = ConfigurationManager.ConnectionStrings["ShoppingZone"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                // Create an instance ofSqlDataAdapter. Spcify the command and the connection
                SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from ProductDetail", connection);
                // Create an instance of DataSet,which is an in-memory datastore for storing tables
                DataSet dataset = new DataSet();
                // Call the Fill() methods, whichautomatically opens the connection, executes the command
                // and fills the dataset withdata, and finally closes the connection.
               dataAdapter.Fill(dataset);
               GridView1.DataSource = dataset;
               GridView1.DataBind();
            }
        }
    }
} 

Output:

disconnected data access model

Post your comments / questions