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
protected void Page_Load(object sender, EventArgs e)
{
string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string strSelect = "SELECT Username FROM Users";
//Create SQL Connection And SQLCommand
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSelect;
con.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dReader.Read())
{
ddlUsers.Items.Add(dReader["Username"].ToString());
}
dReader.Close();
}VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim strSelect As String = "SELECT Username FROM Users"
'Create SQL Connection And SQLCommand
Dim con As New SqlConnection(strConnection)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While dReader.Read()
ddlUsers.Items.Add(dReader("Username").ToString())
End While
dReader.Close()
End Sub
Hope this helps.
If you like this post than join us or share

0 comments:
Post a Comment