public class EmployeeCollection
{
#region Start - private variables
private int _employeeID;
private string _lastName;
private string _firstName;
#endregion
public EmployeeCollection(){}
public int EmployeeID
{
get { return _employeeID; }
set { _employeeID = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}
The Employee
class contains a subset of properties that correspond to the column
names of the Employees table. We will now create a new constructor for
the Employee class. This constructor will allow us to perform some
magic. The constructor will accept a DataRow as a parameter. When the
constructor is called it will set the properties of the Employee class
based on the data in the DataRow parameter. By doing this, you will be
able to construct a collection of employees in a very simple manner.
public Employee (System.Data.DataRow dataRow)
{
/* Enumerate all the properties of this class
* if there is a corresponding column in the data row
* set this class' property to the value of the column in the
* datarow. */
foreach( System.Reflection.PropertyInfo pi in
this.GetType().GetProperties())
{
if (pi.CanWrite)
{
try
{
if (dataRow[ pi.Name ] != null && !dataRow.IsNull( pi.Name ) )
{
pi.SetValue(this, dataRow[ pi.Name ], null);
}
else
{
pi.SetValue(this, null, null);
}
}
catch // DB COLUMN does not exist for this property.
{
pi.SetValue(this, null, null);
}
}
}
}
See this link:
http://www.c-sharpcorner.com/UploadFile/dsandor/SettingClassPropsFromDb11302005064002AM/SettingClassPropsFromDb.aspx