0

currently when the records are zero i am getting the error source cantain no data row to manage that i have checked it count>0 but still i am getting any idea how to solve this.

dynamic dt = ds.Tables(0);
int totalrowCount = dt.Rows.Count;


//dt.Rows.Count 
//dt.Select().Take(100)
// dt.Rows.Cast(Of System.Data.DataRow)().Take(100)
DataTable dt1 = default(DataTable);
if (totalrowCount > 0) {
    dt1 = dt.AsEnumerable().Take(100).CopyToDataTable();
} else {
    dt1 = dt.AsEnumerable().CopyToDataTable();
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It's not clear what you expect the check to do - if there are no rows, then `dt.AsEnumerable().Take(100)` would return the same sequence as `dt.AsEnumerable()`. It doesn't help that we don't know *where* you're getting an error. If it's in a later piece of code which requires a non-empty `DataTable`, then you really need to think more carefully about what you want to happen when there simply *aren't* any rows. – Jon Skeet Jun 06 '17 at 06:57
  • in else part i am getting the error. –  Jun 06 '17 at 06:58
  • @Zbidi i am getting error in else part –  Jun 06 '17 at 06:59
  • Right, `CopyToDataTable` is documented as failing when there are no rows. So maybe you need to find a different way of creating a `DataTable` in that case - maybe just use `dt1 = dt;`? – Jon Skeet Jun 06 '17 at 07:04
  • ok i have used dt.clone and it's working !! thanks for the help @JonSkeet –  Jun 06 '17 at 07:09
  • Okay, will write it up as an answer. – Jon Skeet Jun 06 '17 at 07:12

2 Answers2

1

As documented, CopyToDataTable() can't be called on an empty sequence of rows - presumably because then there's no schema information to include. Instead, if you know your original table is empty and you want a new table with the same schema, just clone it. So you'd have:

DataTable dt = ds.Tables(0);
DataTable newTable = dt.Rows.Count > 0
    ? dt.AsEnumerable().Take(100).CopyToDataTable() 
    : dt.Clone();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
-1

Check number of rows with the following;

if (ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)

however when row nubmer<=0

dt1 = dt.AsEnumerable().CopyToDataTable(); 

This line does not make sense. Do you need to fetch null rows?

Zbidi
  • 116
  • 10
  • 1
    If there were no tables, the code would be failing elsewhere. The OP is successfully checking whether or not there are any rows. – Jon Skeet Jun 06 '17 at 07:04