ExecuteReader
Execute
Reader will be used to return the set of rows, on execution of SQL Query or
Stored procedure using command object. This one is forward only retrieval of
records and it is used to read the table values from first to last.
Before implement this example first design one table UserInformation in your database as
shown below
Column Name
|
Data Type
|
Allow Nulls
|
UserName
|
varchar(50)
|
Yes
|
LastName
|
varchar(50)
|
Yes
|
Location
|
Varchar(50)
|
Yes
|
Once table designed in database enter some dummy data
to test after that write the following code in your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title>Example of
ExecuteReader in asp.net</title>
</head>
<body>
<form id="form1"
runat="server">
<div>
<b>Bind Gridview with
ExecuteReader command object Data</b><br /><br />
<asp:GridView ID="gvUserInfo"
runat="server">
<HeaderStyle BackColor="#df5015"
Font-Bold="true"
ForeColor="White"/>
</asp:GridView>
</div>
</form>
</body>
</html>
|
Now add the following namespaces in code behind
C#
Code
using System;
using System.Data.SqlClient;
using System.Data;
|
After add namespaces write the following code in code
behind
protected void Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new
SqlConnection("Data
Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM
UserInformation", con);
SqlDataReader dr =
cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}
|
VB.NET
Code
Imports System.Data.SqlClient
Imports System.Data
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As
Object, e As EventArgs) Handles
Me.Load
If Not
IsPostBack Then
BindGridview()
End If
End Sub
' This method is used to bind gridview from database
Protected Sub BindGridview()
Using con As New SqlConnection("Data
Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select
UserName,LastName,Location FROM UserInformation", con)
Dim dr As SqlDataReader
= cmd.ExecuteReader()
gvUserInfo.DataSource = dr
gvUserInfo.DataBind()
con.Close()
End Using
End Sub
End Class
|
Demo
If you observe above code I written select query like
getting all the data from UserInfromation
table but whenever we click on button we are getting only one value (First Row
First Column value) and ignoring other row and column values.
No comments:
Post a Comment