1

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();
    }

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.