SqlCommand ExecuteReader Method Example in Asp.Net Using C# And Vb
This method Execute the command and builds or populate the SqlDataReader object. It is used for accessing data when query returns a set of records for display or navigation purpose.
It provides a forward only, read only connected recordset which means it needs open Sql Connection untill DataReader is open.
Common usage of ExecuteReader Method can be populating a dropdownlist or listbox or retrieving binary files from database.
I have also explained NonQuery , Scalar and XmlReader methods.
C# CODE
VB.NET
Hope this helps.
This method Execute the command and builds or populate the SqlDataReader object. It is used for accessing data when query returns a set of records for display or navigation purpose.
It provides a forward only, read only connected recordset which means it needs open Sql Connection untill DataReader is open.
Common usage of ExecuteReader Method can be populating a dropdownlist or listbox or retrieving binary files from database.
I have also explained NonQuery , Scalar and XmlReader methods.
C# CODE
01
protected
void
Page_Load(
object
sender, EventArgs e)
02
{
03
string
strConnection = ConfigurationManager.ConnectionStrings[
"ConnectionString"
].ConnectionString;
04
string
strSelect =
"SELECT Username FROM Users"
;
05
06
//Create SQL Connection And SQLCommand
07
SqlConnection con =
new
SqlConnection(strConnection);
08
SqlCommand cmd =
new
SqlCommand();
09
cmd.Connection = con;
10
cmd.CommandType = CommandType.Text;
11
cmd.CommandText = strSelect;
12
13
con.Open();
14
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
15
while
(dReader.Read())
16
{
17
ddlUsers.Items.Add(dReader[
"Username"
].ToString());
18
}
19
dReader.Close();
20
}
VB.NET
01
Protected
Sub
Page_Load(sender
As
Object
, e
As
EventArgs)
02
Dim
strConnection
As
String
= ConfigurationManager.ConnectionStrings(
"ConnectionString"
).ConnectionString
03
Dim
strSelect
As
String
=
"SELECT Username FROM Users"
04
05
'Create SQL Connection And SQLCommand
06
Dim
con
As
New
SqlConnection(strConnection)
07
Dim
cmd
As
New
SqlCommand()
08
cmd.Connection = con
09
cmd.CommandType = CommandType.Text
10
cmd.CommandText = strSelect
11
12
con.Open()
13
Dim
dReader
As
SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
14
While
dReader.Read()
15
ddlUsers.Items.Add(dReader(
"Username"
).ToString())
16
End
While
17
dReader.Close()
18
End
Sub
Hope this helps.
If you like this post than join us or share
0 comments:
Post a Comment