#region DataGridView分页

DataTable MiddleData = new DataTable();
private void QueryBtn_Click(object sender, EventArgs e)
{

//查询RawData中符合条件的数据
MiddleData = commData.Select(RawData, $"NewTime > '{dateTime1}' and NewTime < '{dateTime2}' ");


PageSorter(MiddleData);
dataGridView1.DataSource = FlipOverData;

}

/// <summary>
/// 每页记录数
/// </summary>
public int pageSize = 22;

/// <summary>
/// 总记录数
/// </summary>
public int recordCount = 0;

/// <summary>
/// 总页数
/// </summary>
public int pageCount = 0;

/// <summary>
/// 当前页
/// </summary>
public int currentPage = 0;

private void PageSorter(DataTable dataTable)
{

// 总记录数
recordCount = dataTable.Rows.Count;
// 总页数
pageCount = recordCount / pageSize;
if (recordCount % pageSize > 0)
{
pageCount++;
}
currentPage = 1;
LoadPage(dataTable);
}
private void LoadPage(DataTable dataTable)
{
//当前页小于1时,当前页=1
if (currentPage < 1) currentPage = 1;
//当前页大于总页数时,当前页=总页数
if (currentPage > pageCount) currentPage = pageCount;
int beginRecord; //开始指针
int endRecord; //结束指针
DataTable dtTemp;
//克隆 DataTable 的结构,包括所有 DataTable 架构和约束。
dtTemp = dataTable.Clone();

beginRecord = pageSize * (currentPage - 1);


if (currentPage == 1) beginRecord = 0;

endRecord = pageSize * currentPage;

if (currentPage == pageCount) endRecord = recordCount;

for (int i = beginRecord; i < endRecord; i++)
{
// dataTable.Rows[i] 复制到 dtTemp 中,保留任何属性设置以及初始值和当前值。
dtTemp.ImportRow(dataTable.Rows[i]);
}

FlipOverData = dtTemp;


labPageIndex.Text = "当前页: " + currentPage.ToString() + " / " + pageCount.ToString();//当前页
labRecordCount.Text = "总行数: " + recordCount.ToString() + " 行";//总记录数
}

/// <summary>
/// 记录翻页用到的数据
/// </summary>
public DataTable FlipOverData { get; set; }

//首页
private void FirstPagBtn_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{ return; }
currentPage = 1;
LoadPage(MiddleData);
dataGridView1.DataSource = FlipOverData;
}

//上一页
private void UpPagBtn_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{ return; }
currentPage--;

LoadPage(MiddleData);
dataGridView1.DataSource = FlipOverData;

}
//下一页
private void NextPagBtn_Click(object sender, EventArgs e)
{
if (currentPage == pageCount)
{ return; }
currentPage++;

LoadPage(MiddleData);
dataGridView1.DataSource = FlipOverData;

}
//尾页
private void LastPagBtn_Click(object sender, EventArgs e)
{
if (currentPage == pageCount)
{ return; }
currentPage = pageCount;

LoadPage(MiddleData);
dataGridView1.DataSource = FlipOverData;

}

#endregion