4

Have a DataTable and I need to create another one having a subset range of rows from the first. So I want the second DataTable to have row n till n + y from the first one. How can I do this please?

DataTable limitData = new DataTable();
for (int rowIndex = startingRow; rowIndex < endingRow; rowIndex++)
{
    limitData.Rows.Add(columnarData.Rows[rowIndex].ItemArray);
}

gives an error: "Input array is longer than the number of columns in this table."

The code is in C# .NET 4.0

Ali
  • 1,462
  • 2
  • 17
  • 32

3 Answers3

3

try this and let me hear from if this works

DataTable limitData =limitData.Clone();
for (int rowIndex = startingRow; rowIndex < endingRow; rowIndex++)
{
    limitData.Rows.Add(columnarData.Rows[rowIndex].ItemArray);
}

or

DataTable limitData =limitData.Clone();
foreach (DataRow dr in columnarData.Rows)
{
    limitData.Rows.Add(dr);
}
Jade
  • 2,972
  • 1
  • 11
  • 9
  • Ok, it works now. But is it better to use Rows.Add(columnarData.ImportRow([rowIndex]) ? as suggested by @geek – Ali Dec 20 '13 at 10:54
  • i don't know the performance but it may also serves the same purpose. See also my updates I added a new option and there might be other simplier solutions out there. – Jade Dec 20 '13 at 11:02
  • No Need to make for loop to transfer data , you just need to put SourceDT=DestinationDT.Copy(); – Ahmad Hindash Apr 29 '19 at 13:31
0

try this

for (DataRow r in dt.Rows)
    {
       if(some condition))
       {
          extractedData.ImportRow(r);
       }
    }
santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • Can I use and index into the dt. There is no if condition to restrict to. I need a subset of rows. – Ali Dec 20 '13 at 10:37
  • 1
    If I use ImportRow in my code, it adds the rows but there are no columns! – Ali Dec 20 '13 at 10:48
0

Union() also work:

dt1 = dt1.AsEnumerable().Union(dt2.AsEnumerable()).CopyToDataTable();

Reference from this post.

yu yang Jian
  • 6,680
  • 7
  • 55
  • 80