Follow in Twitter & Facebook



Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools



Thursday, August 30, 2012

DataReader example in Asp.Net

In this article we will discuss about asp.net datareader and we will see one example of that. You can also check my laster article on difference between datareader and dataset in asp.net.

DataReader:
- It works in connected architecture mode, so it needs an active connection. You can check my last article on Connected and Disconnected Architecture Ado.Net.

- It supports forward only and read only access.

- Performance is better in case of data access using datareader.
- ExecuteReader() method of the Command object is used while working with datareader.

Example:

In this example we will check how to bind a dropdownlist using datareader.

Html code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataReaderExample.aspx.cs"
Inherits="DataReaderExample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>DataReader example in Asp.Net</title></head><body><form id="form1" runat="server"><div>Category:<asp:DropDownList ID="ddlCategory" runat="server"></asp:DropDownList>
</div>
</form>
</body></html>
.cs code:

void BindCategory(){
ddlCategory.Items.Clear();

string strSQL = "SELECT categoryName, categoryID FROM Category";
SqlConnection con = new SqlConnection("Connection string will go here");
SqlCommand cmd = new SqlCommand(strSQL, con);
SqlDataReader dr;
try{
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read()){

ListItem item = new ListItem();item.Text = dr[
"categoryName"].ToString();item.Value = dr[
"categoryID"].ToString();ddlCategory.Items.Add(item);
}
dr.Close();
}

catch (Exception ex){

//Handle exception here}
finally{
con.Close();
}

You can also check one article on connection pooling in asp.net also check about joins in sql server 2008.




0 on: "DataReader example in Asp.Net"