C# ADO.NET OleDbDataReader

The OleDbDataReader Object in C# provides a connection-oriented data access to OLEDB Data Sources through C# applications.

ExecuteReader() method

To retrieve data using the OleDbDataReader, you typically use the ExecuteReader() method in the OleDbCommand Object. This method sends the SQL statements or Stored Procedures to the associated OleDbConnection Object and populates an OleDbDataReader Object based on the executed SQL statement.

When the ExecuteReader method is executed on the OleDbCommand Object, it instantiates an OleDb.OleDbDataReader Object. This OleDbDataReader Object serves as a cursor that allows you to efficiently read and access the retrieved data.

OleDbDataReader oledbReader = oledbCmd.ExecuteReader();

Before reading from the OleDbDataReader, it's important to ensure that the OleDbDataReader is open and positioned prior to the first record. You can achieve this by invoking the Read() method, which advances the OleDbDataReader to the next row and returns a boolean value indicating whether there are more rows available.

Read() method

The Read() method of the OleDbDataReader is used to sequentially read the rows from the OleDbDataReader. It always moves the cursor forward to the next valid row, if any rows exist.

OleDbDataReader.Read()

By invoking the Read() method in a loop, you can retrieve the data from each row and access the values of individual columns using the appropriate getter methods (e.g., GetString(), GetInt32(), etc.) based on the data type.

Full Source C#
using System; using System.Windows.Forms; using System.Data.OleDb; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; OleDbConnection oledbCnn ; OleDbCommand oledbCmd ; string sql = null; connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"; sql = "Your SQL Statement Here like Select * from product"; oledbCnn = new OleDbConnection(connetionString); try { oledbCnn.Open(); oledbCmd = new OleDbCommand(sql, oledbCnn); OleDbDataReader oledbReader = oledbCmd.ExecuteReader(); while (oledbReader.Read ()) { MessageBox.Show(oledbReader.GetValue(0) + " - " + oledbReader.GetValue(1) + " - " + oledbReader.GetValue(2)); } oledbReader.Close(); oledbCmd.Dispose(); oledbCnn.Close(); } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); } } } }

Conclusion

The OleDbDataReader Object in C# enables connection-oriented data access to OLEDB Data Sources. It is instantiated using the ExecuteReader() method in the OleDbCommand Object and provides methods like Read() to sequentially retrieve and access data rows. Ensuring the OleDbDataReader is open and positioned correctly before reading is essential, and proper management of the connection and closing of the OleDbDataReader and OleDbConnection is necessary when done reading the data.