在C#中使用Table進行數據分頁通常是通過使用類似于DataGridView或者ListView這樣的控件來展示數據,并且結合使用Paging類或者自定義的分頁邏輯來實現分頁功能。以下是一個簡單的示例:
using System;
using System.Windows.Forms;
public partial class Form1 : Form
{
private DataTable dataTable;
private int pageSize = 10;
private int currentPage = 1;
public Form1()
{
InitializeComponent();
LoadData();
DisplayData();
}
private void LoadData()
{
// Load data from database or any other source
// For demo purpose, we will create a sample DataTable
dataTable = new DataTable();
// Add columns to the DataTable
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
// Add rows to the DataTable
for (int i = 1; i <= 100; i++)
{
dataTable.Rows.Add(i, "Name " + i);
}
}
private void DisplayData()
{
// Clear existing rows in the DataGridView
dataGridView1.Rows.Clear();
// Calculate start and end index of the current page
int startIndex = (currentPage - 1) * pageSize;
int endIndex = Math.Min(startIndex + pageSize, dataTable.Rows.Count);
for (int i = startIndex; i < endIndex; i++)
{
// Add a row to the DataGridView for each data row
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView1, dataTable.Rows[i]["ID"], dataTable.Rows[i]["Name"]);
dataGridView1.Rows.Add(row);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
currentPage++;
DisplayData();
}
private void btnPrevious_Click(object sender, EventArgs e)
{
currentPage--;
DisplayData();
}
}
在此示例中,我們創建了一個包含ID和Name列的DataTable,并填充了100條數據。然后,我們通過點擊“Next”和“Previous”按鈕來切換不同頁數的數據。您可以根據需要自定義分頁邏輯,并根據實際需求調整代碼。