Friday, July 24, 2015

Asp.net Interview Question: Difference between DataReader and DataAdapter

In this article I am going to differentiate DataReader and DataAdapter


DataReader:
DataReader is a Connection Oriented means require a continuous connection with the data source to accessing it. It is read and forward only. We can’t write/customize the data. It is best choice where we need to display the data only. It is fast as compared to dataset. It stores one row in memory at a time.

Example:
C#:
public void BindGridview()
    {      
   SqlCommand cmd = new SqlCommand("Select * from Student_Detail", con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();        
        GridView1.DataSource = dr;
        GridView1.DataBind();
        con.Close();
}

VB:
  Public Sub BindGridview()
   Dim cmd As New SqlCommand("Select * from Student_Detail", con)
            con.Open()
            Dim dr As SqlDataReader = cmd.ExecuteReader()
            GridView1.DataSource = dr
            GridView1.DataBind()
            con.Close()
End Sub

DataAdapter:
DataAdapter is a disconnected oriented means it does not require a continuous connection with the data source to accessing it. DataAdapter will act as bridge between dataset and database for retrieve and save the data. It fetches the data from database and fills the dataset/datatable. It is slow compare to DataReader.  

Example:
C#:
public void BindGridview()
    {
SqlDataAdapter adp = new SqlDataAdapter("Select * from dbo.Student_Detail", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();   
}

VB:
  Public Sub BindGridview()
  Dim adp As New SqlDataAdapter("Select * from dbo.Student_Detail", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
End Sub

    In this article i have explained commonly asked interview question difference between DataReader and DataAdapter in asp.net. I hope you enjoyed this article. 

No comments:

Post a Comment