Thursday, December 11, 2008

 

DataTable.SelectRows(n)

Doing a DataTable.Select() in ADO.NET is like using a Where clause in T-SQL, but you'd have noticed that Data table lacks a way to retrieve only specific number of rows. Well this can be easy to work around using a Top N clause in T-SQL but can be tricky in case when the data is read from different sources like XML files, Web Services etc.

Steven Smith shows a little code-snippet that can be used to work around this, so I decided to use that.

I went a step ahead and added the method to my Extension methods library as below.

public static DataTable SelectRows(this DataTable dataTable, int rowCount)
{
    try
    {
        DataTable myTable = dataTable.Clone(); 
        DataRow[] myRows = dataTable.Select();
        for (int i = 0; i < rowCount; i++)
        {
            if (i < myRows.Length)
            {
                myTable.ImportRow(myRows[i]);
                myTable.AcceptChanges();
            }
        }
 
        return myTable;
 
    }
    catch (Exception)
    {
        return new DataTable();
    }
}

So for example it can be used as follows.



GridView.DataSource = MyDataTable.SelectRows(5);
GridView.DataBind();

Labels: , ,


This page is powered by Blogger. Isn't yours?