In this article I will explain with an example, how to implement
SqlDataAdapter in
ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of following control:
GridView – For displaying data.
Columns
The
GridView consists of three
BoundField columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Implementing SqlDataAdapter in ASP.Net using C# and VB.Net
Inside the Page_Load event handler, first the connection string is read from the Web.Config file and the SELECT query is defined.
Then, a connection to the database is established using the SqlConnection class.
The SqlDataAdapter object is initialized with the SqlCommand and using the Fill function, the DataSet is populated with the records from database.
Finally, the
DataSet is assigned to the
DataSource property of
GridView and the
GridView is populated.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
gvCustomers.DataSource = ds;
gvCustomers.DataBind();
}
}
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim sql As String = "SELECT CustomerId, Name, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using ds As DataSet = New DataSet()
sda.Fill(ds)
gvCustomers.DataSource = ds
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End If
End Sub
Screenshot
Downloads