[C#][WinForm] DataGridView 簡易分頁範例
在 WinForm 中,想將 DataGridView 進行分頁的話
就得自己處理了,不像 WebForm 的 DataGridView 有分頁設定。
首先介面設計 (還是使用北風資料庫來作範例)
接著來進行程式碼的部分,先宣告三個整數,與計算分頁數的功能
private int CurrentPageIndex = 1; //現在選取的分頁編號
private int TotalPage = 0; //總共多少分頁
//計算頁數
private void CalculateTotalPages(DataTable dt)
{
int rowCount = dt.Rows.Count;
TotalPage = rowCount / PageSize;
//不足一個分頁行數的還是算一頁
if (rowCount % PageSize > 0)
TotalPage += 1;
}
然後利用 SQL 來取得現在的分頁資料
private DataTable GetCurrentRecords(int page)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnecString))
{
SqlCommand cmd = new SqlCommand();
if (page == 1)
{
cmd = new SqlCommand("Select TOP " + PageSize +
" [OrderID],[CustomerID],[ShipVia],[Freight] FROM [Northwind].[dbo].[Orders] ORDER BY [OrderID]", con);
}
else
{
//利用 SQL 語法來切換資料
int PreviousPageOffSet = (page - 1) * PageSize;
cmd = new SqlCommand("Select TOP " + PageSize + " [OrderID],[CustomerID],[ShipVia],[Freight] " +
"FROM [Northwind].[dbo].[Orders] WHERE [OrderID] "+
"NOT IN " +
"(Select TOP " + PreviousPageOffSet +" [OrderID] from [Northwind].[dbo].[Orders] ORDER BY [OrderID] ) "
, con);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
lbCurrentPage.Text = "第 " + CurrentPageIndex + " 頁";
}
return dt;
}
最後切換分頁的功能了
{
if (this.CurrentPageIndex > 1)
{
CurrentPageIndex--;
dataGridView1.DataSource =GetCurrentRecords(CurrentPageIndex);
}
}
private void btnNxtPage_Click(object sender, EventArgs e)
{
if (CurrentPageIndex < TotalPage)
{
CurrentPageIndex++;
dataGridView1.DataSource = GetCurrentRecords(CurrentPageIndex);
}
}
private void btnFirstPage_Click(object sender, EventArgs e)
{
CurrentPageIndex = 1;
dataGridView1.DataSource = GetCurrentRecords(CurrentPageIndex);
}
private void btnLastPage_Click(object sender, EventArgs e)
{
CurrentPageIndex = TotalPage;
dataGridView1.DataSource = GetCurrentRecords(CurrentPageIndex);
}
補上連結資料庫的部分,就是還沒分頁的全部資料
{
using (SqlConnection con = new SqlConnection(ConnecString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT [OrderID],[CustomerID],[ShipVia],[Freight] FROM [Northwind].[dbo].[Orders] ORDER BY [OrderID]", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
最後的分頁設定了,這個功能就更新一下分頁列數,然後重新呼叫 Function
{
if (PageSize != Convert.ToInt32(nudPageSize.Value))
{
CurrentPageIndex = 1;
PageSize = Convert.ToInt32(nudPageSize.Value);
CalculateTotalPages(getData());
lbTotalPage.Text = "共 " + TotalPage + " 頁";
lbCurrentPage.Text = "第 " + CurrentPageIndex + " 頁";
dataGridView1.DataSource = GetCurrentRecords(CurrentPageIndex);
}
}
執行畫面:
範例檔案 下載