How to Fill Your Own Dynamic Objects using ADO.NET

Sometimes you need to use information of different types like strings, booleans or doubles in the same data structure. In that case you would like to be able to create your own objects to fulfill your needs. But if you had to create 5 thousand different objects you wouldn't be too happy to do that by coding each one of them in a static way. You would like to fill the data in each one of the objects dynamically and most probably using databases.

If you create your own object and you can fill it with the data you want, then you are ready to get your job done. The use of the OleDbDataReader is sometimes better than using OleDbDataAdapter because you have better control of what you are doing. Follow the next steps and enjoy using your own data types.

Step #1: Add the following statement at the top of your source code

using System.Data.OleDb;

Step #2: Declare the following things you will use to read data from a database

OleDbCommand cmd = new OleDbCommand();
OleDbDataReader reader;

Step #3: Open the database connection

myConnection.Open();

Step #4: Configure the OleDbCommand properties

cmd.Connection = myConnection;
cmd.CommandText = "SELECT A, B, C, D FROMaTable WHERE A = Yes";

Step #5: Instantiate the reader with the data returned by the OleDbCommand

reader = cmd.ExecuteReader();

Step #6: Create an array of objects of the class you defined

using System;
namespace myNamespace
{
public class myClass
{
public int A;
public String B;
public bool C;
public bool D; 

public myClass()
{
A = 0;
B = "0";
C =
false;
D =
false;
}
}
}  

myClass[] arrMyClass = new myClass[150]; 


Step #7: Loop through the OleDbDataReader to get the information you need and fill the object array 

int row = 0;
while(reader.Read())
{
int getA = reader.GetInt32(0);
String getB = reader.GetString(1);
bool getC = reader.GetBoolean(2);
bool getD = reader.GetBoolean(3);
arrMyClass[row].A = getA;
arrMyClass[row].B = getB;
arrMyClass[row].C = getC;
arrMyClass[row].D = getD;
row++;
// Counts how many rows are being read
}
reader.Close();
// It is important to close the OleDbDataReader 

Up Next
    Ebook Download
    View all
    Learn
    View all