Tuesday, June 5, 2012

Find a Record on DataTable


Problem:

          There are situations where we need to find some records on the DataTable. To find a record, DataTable providesFind() method(with 2 overloads). However, in order to use this method we need to set the PrimaryKey. Most of the times we use DataTable instance to store returned result of some business logic methods and we may not know the structure of the table to set PrimaryKey. For example, cosider the code:
DataTable studentsData = StudentManager.getStudentsByClassID(100);
...
...
DataTable departments = DepartmentManager.getDepartmentsByID(4);
In both of the DataTable instances studentsData and departments, we are not defining the structure of the table and there by not setting the PrimaryKey.  If you try to use the Find() method here, you will get the exception MissingPrimaryKeyException (Table doesn't have a primary key):
...
DataTable studentsData = StudentManager.getStudentsByClassID(100);
DataRow dr = studentsData.Rows.Find("Jhon"); //MissingPrimaryKeyException - Table doesn't have a primary key
...
Solution: 

          We can overcome from this limitation by making use of the extension method like this:
public static class DataRowExtensions
{
    public static DataRow FindRecord(this DataRowCollection data, string keyField, string txtToFind)
    {
        foreach (DataRow dr in data)
        {
            if (txtToFind.ToUpper() == dr[keyField].ToString().ToUpper())
                return dr;
        }
        return null;
    }
}
Now we can use FindRecord method to find a record by passing appropriate column name of the value we are passing:
DataTable StudentsData = StudentManager.getStudentsByClassID(100);
DataRow dr = StudentsData.Rows.FindRecord("ST_FirstName","Jhon");
...
...
DataTable Departments = DepartmentManager.getDepartmentsByID(4);
dr = Departments.Rows.FindRecord("DPT_Name","CS");
On any page we can use this extension method by including its namespace. So, our final code looks very simple and easily understandable.

No comments:

Post a Comment