C DataTable Paging Process Instance Code

  • 2021-12-19 06:33:10
  • OfStack

Sometimes when the amount of data we get from the database is too large, and we don't need to display so much at once, we have to paginate the data, so that each page displays different data.


public DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)//PageIndex Indicates which page, PageSize Represents the number of records per page 
  {
   if (PageIndex == 0)
    return dt;//0 Page represents each page of data and returns directly 

   DataTable newdt = dt.Copy();
   newdt.Clear();//copy dt Framework of 

   int rowbegin = (PageIndex - 1) * PageSize;
   int rowend = PageIndex * PageSize;

   if (rowbegin >= dt.Rows.Count)
    return newdt;// If the number of source data records is less than or equal to the records to be displayed, return directly dt

   if (rowend > dt.Rows.Count)
    rowend = dt.Rows.Count;
   for (int i = rowbegin; i <= rowend - 1; i++)
   {
    DataRow newdr = newdt.NewRow();
    DataRow dr = dt.Rows[i];
    foreach (DataColumn column in dt.Columns)
    {
     newdr[column.ColumnName] = dr[column.ColumnName];
    }
    newdt.Rows.Add(newdr);
   }
   return newdt;
  }

Related articles: