Monday, April 2, 2012

ADO.Net - Using DataTable.Select to Filter Rows

The DataTable.Select() method can be used to filter data from a DataTable in the Client side. The DataTable.Select() is flexible enough to accept any number of filters, it takes in the Filter condition as a parameter and returns an array of DataRows which satisfy the filter condition.

Syntax:
public DataRow[] Select(string filterExpression)

Ok, now let us walk through an example of how to use the DataTable.Select() method to filter data from a DataTable.

strQuery = "SELECT EMP_ID, EMP_NAME, SALERY FROM EMPLOYEE;

DataSet dsEmpInfo = DataAccessLayer.GetDataSet(strQuery, "dtEmpInfo");
if (dsEmpInfo.Tables["dtEmpInfo "].Rows.Count > 0)
{
DataRow[] drEmpInfo = dsEmpInfo.Tables["dtEmpInfo "].Select("SALERY ='5000'");
}

The above filter will retrieve the list of employees who receive a salery of 5000 from the DataTable, once the rows are filtered out we can use a foreach loop to interate through the rows for processing.

foreach (DataRow dr in drEmpInfo)
{
// Process Rows here
Response.Write(dr["EMP_NAME"].ToString());
}


It is advisable to use the DataTable.Select() method only when you expect the result of the search to return more number of rows, and when the search is complex involving more that one search criteria.

When the search is intended to return only a single row, the DataTable.Rows.Find() method offers better performance when comared to the DataTable.Select() method.

That’s it we have used the DataTable.Select() method to filter rows from a client side DataTable.


Search Flipkart Products:
Flipkart.com

No comments: