Converting DataRow Array to DataTable

Here's a little function I wrote the other day that I think might be helpful for some of you.
I was filtering a datatable using the DataTable.Select method. The Select method returns the filtered rows as an array of DataRow objects, but I wanted the result of the filter to be a Datable object containing the filtered rows, so I wrote a function that does this for me.

public DataTable FilterTable(DataTable dt, string filterString)
        {
            DataRow[] filteredRows=dt.Select(filterString);
            DataTable filteredDt=dt.Clone();

            DataRow dr;
            foreach(DataRow oldDr in filteredRows)
            {
                dr=filteredDt.NewRow();
                for(int i=0;i<dt.Columns.Count;i++)
                    dr[dt.Columns[i].ColumnName]=oldDr[dt.Columns[i].ColumnName];
                filteredDt.Rows.Add(dr);

            }

            return filteredDt;
        }
        

HTH
Published Saturday, March 04, 2006 12:05 AM by admin
Filed Under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Converting DataRow Array to DataTable @ Wednesday, March 22, 2006 5:31 PM

why must you create a column objects for each row? that does't seem to be efficient

this might be more efficient

foreach ( DataRow oldDr in filteredRows ) {
filteredDt.ImportRow(oldDr);
}
return filteredDt;

abods

# re: Converting DataRow Array to DataTable @ Thursday, April 20, 2006 10:38 PM

Thanks,
I was searching for this option very eagrly.
Its working properly with import rows method.
I was getting error when i am going to add rows to table. But now it works

Tushar

# re: Converting DataRow Array to DataTable @ Tuesday, May 23, 2006 5:06 AM

As I know that the clone method will take a copy of the datatable ,so at the end of your code you will have the main datatable dt + the filtered rows.

Wissam Bishouty

# re: Converting DataRow Array to DataTable @ Monday, September 17, 2007 2:12 AM

That very useful for me. Thank you for your nice code.

GobElmo

# re: Converting DataRow Array to DataTable @ Tuesday, December 11, 2007 11:33 PM

Hi ,
    i have done that already but it is very slow  to loop all the records to add in to the table.i m looking for the direct method to add all the rows in one shot. i know this is possible but how ?

Thanks

Zalak Shah

What do you think?

(required) 
required 
optional
required