Search code examples
c#asp.netgridviewtake

source cantain no data row while using take asp.net


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

Solution

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