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:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article