user1326293
user1326293

Reputation: 923

Adding DataRow object to DataTable in C#

I'm trying to loop through my database looking for specific rows with date ranges. Whenever I try to use DataTable.Import(DataRow) it adds a new row with no values inside. How do I "import" a DataRow into a DataTable? Here is the loop, thanks!

        public DataTable FilterDataTableByDates(DataTable td, DateTime from, DateTime to)
    {
        DataTable tempTd = new DataTable();
        foreach (DataRow dr in td.Rows)
        {
            long ticks = Convert.ToInt64(dr["cpd_date"].ToString());
            if (ticks > from.Ticks && ticks < to.Ticks)
            {
                tempTd.ImportRow(dr);
            }
        }
        return tempTd.Copy();
    }

Upvotes: 1

Views: 7833

Answers (1)

aleroot
aleroot

Reputation: 72636

You can use the Add method to copy a DataRow from one datatable to another :

tempTd.Rows.Add(dr.ItemArray);

Even your method could work but you have to create your DataTable coping the structure from the origin :

DataTable tempTd = td.Clone();

With the Clone() method you create a new datatable with the same structure of the original datatable, then you can import row in it.

So your complete method will become :

public DataTable FilterDataTableByDates(DataTable td, DateTime from, DateTime to)
{
    DataTable tempTd = td.Clone();
    foreach (DataRow dr in td.Rows)
    {
        long ticks = Convert.ToInt64(dr["cpd_date"].ToString());
        if (ticks > from.Ticks && ticks < to.Ticks)
        {
            tempTd.ImportRow(dr);
        }
    }
    return tempTd.Copy();
}

Upvotes: 2

Related Questions