1.

What is Data Reader and how we bind data to DataReader?

Answer»

DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results from the Data Sources , which do not update the data. The DataReader cannot be created directly from code, they can created only by calling the EXECUTEREADER method of a Command Object.

SqlDataReader sqlReader = sqlCmd.ExecuteReader();

The DataReader Object provides a connection oriented data access to the Data Sources. A Connection Object can contain only one DataReader at a time and the connection in the DataReader REMAINS open, also it cannot be used for any other purpose while data is being accessed. When we started to read from a DataReader it should always be open and POSITIONED prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist .

DataReader.Raed();

Below is the sample code on how to bind data to DataReader:

public partial class Form1 : Form    {        public Form1()        {            INITIALIZECOMPONENT();        }        private void button1_Click(object sender, EventArgs e)        {            string connetionString = null;            SqlConnection sqlCnn ;            SqlCommand sqlCmd ;            string sql = null;            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;USER ID=UserName;Password=Password";            sql = "Your SQL Statement Here , like Select * from product";            sqlCnn = new SqlConnection(connetionString);            try            {                sqlCnn.Open();                sqlCmd = new SqlCommand(sql, sqlCnn);                SqlDataReader sqlReader = sqlCmd.ExecuteReader();                while (sqlReader.Read())                {                    MessageBox.Show(sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1) + " - " + sqlReader.GetValue(2));                }                sqlReader.Close();                sqlCmd.Dispose();                sqlCnn.Close();            }            catch (Exception ex)            {                MessageBox.Show("Can not open connection ! ");            }        }    }


Discussion

No Comment Found