C# 分頁控制元件
阿新 • • 發佈:2019-02-06
介面:
程式碼:
using System;
using System.Collections.Generic;using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Data.SqlClient;
namespace wyyNavigator
{
public partial class wyyNavigator : UserControl
{
#region 變數定義
private int totalCount = 0;//總資料個數
private int pageCount = 0;//總頁數
private int currentPageIndex = 1;//當前頁索引
private int pageSize = 10;//每頁分頁大小
private int remainder = 0;//最後一頁剩餘個數
private bool isAutoUpdateLabelTip = true;//獲取或設定是否自動更新分頁標籤內容提示,預設為true
private string sqlAddress = "";//"Data Source=192.168.100.144;Initial Catalog=test;User ID=sa;Password=123456;";//DataGridViewd要繫結的表名
private string tableName = "";//"DataSource";//DataGridViewd要繫結的表名
private string strWhere = "";
private DataSet dsAll = null;//總資料來源
#endregion
#region 傳入引數
#region 通過資料[庫]查詢
/// <summary>
/// 連結資料庫地址
/// </summary>
public string SqlAddress
{
get { return this.sqlAddress; }
set { this.sqlAddress = value; base.Refresh(); }
}
/// <summary>
/// 查詢表
/// </summary>
public string TableName
{
get { return this.tableName; }
set { this.tableName = value; base.Refresh(); }
}
/// <summary>
/// 新增自定義條件
/// </summary>
public string StrWhere
{
get { return this.strWhere; }
set { this.strWhere = value; base.Refresh(); }
}
#endregion
#region 通過資料[源]查詢
/// <summary>
/// 傳遞dataset資料來源
/// </summary>
public DataSet DsAll
{
get { return this.dsAll; }
set { this.dsAll = value; base.Refresh(); }
}
#endregion
#region 外調函式
/// <summary>
/// 繫結資料
/// </summary>
public void dataBand()
{
comboBoxNum();
showDataGirdView();
}
/// <summary>
/// 返回當前頁面資料
/// </summary>
/// <returns></returns>
public DataGridView outputDGV()
{
return dataGridView_show;
}
#endregion
#endregion
#region 載入
//定義委託
public delegate void BindHandle(object sender, EventArgs e);
/// <summary>
/// 繫結資料來源事件
/// </summary>
//public event BindHandle BindSource;
public wyyNavigator()
{
InitializeComponent();
}
#endregion
//載入事件
private void wyyNavigator_Load(object sender, EventArgs e)
{
comboBoxNum();
showDataGirdView();
}
#region 分頁操作
//首頁
private void label_first_Click(object sender, EventArgs e)
{
currentPageIndex = 1;
showDataGirdView();
}
//末頁
private void label_end_Click(object sender, EventArgs e)
{
currentPageIndex = pageCount;
showDataGirdView();
}
//上一頁
private void label_up_Click(object sender, EventArgs e)
{
if (currentPageIndex <= pageCount && currentPageIndex != 1)
{
currentPageIndex--;
showDataGirdView();
}
if (isAutoUpdateLabelTip)
{
updateSplitPageLabelTip();
}
}
//下一頁
private void label_down_Click(object sender, EventArgs e)
{
if (currentPageIndex < pageCount && currentPageIndex != pageCount)
{
currentPageIndex++;
showDataGirdView();
}
if (isAutoUpdateLabelTip)
{
updateSplitPageLabelTip();
}
}
//第幾頁
private void comboBox_page_DropDownClosed(object sender, EventArgs e)
{
currentPageIndex = int.Parse(comboBox_page.Text.ToString());
updateSplitPageLabelTip();
showDataGirdView();
}
//每頁條數
private void comboBox_num_DropDownClosed(object sender, EventArgs e)
{
pageSize = int.Parse(comboBox_num.Text.ToString());
//初始化頁碼為1
currentPageIndex = 1;
updateSplitPageLabelTip();
showDataGirdView();
}
//跳轉指定頁
private void button_go_Click(object sender, EventArgs e)
{
try
{
currentPageIndex = int.Parse(textBox_num.Text);
}
catch
{
currentPageIndex = 1;
}
currentPageIndex = currentPageIndex > pageCount ? pageCount : currentPageIndex;
updateSplitPageLabelTip();
showDataGirdView();
}
//修改顯示資料
public void updateSplitPageLabelTip()
{
pagingShow();
comboBoxPage();
comboBoxNum();
}
//判斷顯示狀狀況
private void pagingShow()
{
//共多少頁
pageCount = totalCount / pageSize;
remainder = totalCount % pageSize;
pageCount = remainder == 0 ? pageCount : pageCount + 1;
if (pageCount <= 1)
{
label_first.Enabled = false;
label_end.Enabled = false;
label_up.Enabled = false;
label_down.Enabled = false;
comboBox_page.Enabled = false;
textBox_num.Enabled = false;
button_go.Enabled = false;
}
else
{
label_first.Enabled = true;
label_end.Enabled = true;
label_up.Enabled = true;
label_down.Enabled = true;
comboBox_page.Enabled = true;
textBox_num.Enabled = true;
button_go.Enabled = true;
}
//首頁關閉首頁,上一頁
if (currentPageIndex == 1)
{
label_first.Enabled = false;
label_up.Enabled = false;
}
else
{
label_first.Enabled = true;
label_up.Enabled = true;
}
//末頁關閉末頁,下一頁
if (currentPageIndex == pageCount)
{
label_end.Enabled = false;
label_down.Enabled = false;
}
else
{
label_end.Enabled = true;
label_down.Enabled = true;
}
//共多少條
label_count.Text = "總" + totalCount + "條/" + pageCount + "頁";
textBox_num.Text = currentPageIndex.ToString();
}
//多少頁
private void comboBoxPage()
{
comboBox_page.Items.Clear();
for (int i = 1; i <= pageCount; i++)
{
comboBox_page.Items.Add(i.ToString());
}
comboBox_page.SelectedIndex = -1;
//當為一頁,就設定設定為0
comboBox_page.SelectedIndex = pageCount == 1 ? 0 : currentPageIndex - 1;
}
//每頁多少條
private void comboBoxNum()
{
comboBox_num.Items.Clear();
comboBox_num.Items.Add("10");
comboBox_num.Items.Add("20");
comboBox_num.Items.Add("50");
comboBox_num.Items.Add("100");
comboBox_num.Items.Add("500");
comboBox_num.Items.Add("1000");
comboBox_num.SelectedIndex = 0;
int i = 0;
switch (pageSize)
{
case 10:
i = 0;
break;
case 20:
i = 1;
break;
case 50:
i = 2;
break;
case 100:
i = 3;
break;
case 500:
i = 4;
break;
case 1000:
i = 5;
break;
default:
break;
}
comboBox_num.SelectedIndex = i;
}
//獲取資料
#endregion
#region 資料處理
//繫結資料
private void showDataGirdView()
{
DataTable dt = new DataTable();
if (dsAll != null)
{
dt = GetDsAll();//獲取傳入資料
}
else
{
dt = GetTable();//獲取資料庫資料
}
try
{
//繫結前臺控制元件
totalCount = int.Parse(dt.Rows[0]["total"].ToString());
}
catch
{
totalCount = 1;
}
updateSplitPageLabelTip();
//繫結資料
dataGridView_show.DataSource = dt;
dataGridView_show.AllowUserToAddRows = false;
}
/// <summary>
/// 獲取資料庫分頁查詢
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
private DataTable GetTable(string sql = "")
{
DataTable dt = new DataTable();
try
{
SqlConnection Connection = new SqlConnection(sqlAddress);
Connection.Open();
//分頁查詢
if (sql == "")
{
sql = " ,(SELECT COUNT(1) FROM " + tableName + ") as total ";
sql = "SELECT TOP " + pageSize + " * " + sql + " FROM " + tableName + " WHERE ID NOT IN(SELECT TOP " + ((currentPageIndex - 1) * pageSize) + " ID FROM " + tableName + ")";
}
SqlDataAdapter adpater = new SqlDataAdapter(sql, Connection);
DataSet ds = new DataSet();
adpater.Fill(ds);
adpater.Fill(dt);
Connection.Close();
}
catch
{
label_count.Text = "無資料";
}
return dt;
}
/// <summary>
/// 獲取資料來源分頁查詢
/// </summary>
/// <returns></returns>
private DataTable GetDsAll(string sql = "")
{
DataTable dt = new DataTable();
try
{
dt = DataSetHelper.SplitDataSet(dsAll, pageSize, currentPageIndex).Tables[0];
//新增一列返回總數‘total’
int count = dsAll.Tables[0].Rows.Count;
dt.Columns.Add("total", typeof(int));
foreach (DataRow dr in dt.Rows)
{
dr["total"] = count;
}
}
catch
{
label_count.Text = "無資料";
}
return dt;
}
#region DataSet分頁查詢
public class DataSetHelper
{
public static DataSet SplitDataSet(DataSet ds, int pageSize, int pageIndex)
{
DataSet vds = new DataSet();
vds = ds.Clone();
if (pageIndex < 1) pageIndex = 1;//如果小於1,取第一頁
//if ((ds.Tables[0].Rows.Count + pageSize) <= (pageSize * pageIndex)) pageIndex = 1;
int fromIndex = pageSize * (pageIndex - 1);//開始行
int toIndex = pageSize * pageIndex - 1; //結束行
for (int i = fromIndex; i <= toIndex; i++)
{
if (i >= (ds.Tables[0].Rows.Count)) //到達這一行,退出
break;
vds.Tables[0].ImportRow(ds.Tables[0].Rows[i]);
}
ds.Dispose();
return vds;
}
/// <summary>
/// 根據索引和pagesize返回記錄
/// </summary>
/// <param name="dt">記錄集 DataTable</param>
/// <param name="PageIndex">當前頁</param>
/// <param name="pagesize">一頁的記錄數</param>
/// <returns></returns>
public static DataTable SplitDataTable(DataTable dt, int PageIndex, int PageSize)
{
if (dt == null)
{
return null;
}
if (PageIndex == 0)
return dt;
DataTable newdt = dt.Clone();
//newdt.Clear();
int rowbegin = (PageIndex - 1) * PageSize;
int rowend = PageIndex * PageSize;
if (rowbegin >= dt.Rows.Count)
return newdt;
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;
}
public static DataTable ToDataTable(DataRow[] rows)
{
if (rows == null || rows.Length == 0)
{
return null;
}
DataTable tmp = rows[0].Table.Clone(); // 複製DataRow的表結構
foreach (DataRow row in rows)
{
tmp.Rows.Add(row.ItemArray); // 將DataRow新增到DataTable中
}
return tmp;
}
}
#endregion
#endregion
#region dataGridView操作
//匯出整頁資料
private void ToolStripMenuItem_page_data_Click(object sender, EventArgs e)
{
DataGridViewToExcel(dataGridView_show, progressBar_export);
}
//匯出所有資料
private void ToolStripMenuItem_all_data_Click(object sender, EventArgs e)
{
DialogResult dlg = MessageBox.Show("如果資料量過大需要時間長久,請耐心等待! ", "提示 ", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlg == DialogResult.Yes)
{
dataGridView_show.DataSource = dsAll;
DataGridViewToExcel(dataGridView_show, progressBar_export);
}
}
#endregion
#region 匯出資料到EXCEL
/// <summary>
/// 資料匯出excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="tempProgressBar"></param>
public static void DataGridViewToExcel(DataGridView dgv, ProgressBar tempProgressBar)
{
#region 驗證可操作性
//申明儲存對話方塊
SaveFileDialog dlg = new SaveFileDialog();
//默然檔案字尾
dlg.DefaultExt = "xlsx";
//檔案字尾列表
dlg.Filter = "EXCEL檔案(*.XLS)|*.xlsx";
//默然路徑是系統當前路徑
dlg.InitialDirectory = Directory.GetCurrentDirectory();
//開啟儲存對話方塊
if (dlg.ShowDialog() == DialogResult.Cancel) return;
//返回檔案路徑
string fileNameString = dlg.FileName;
//驗證strFileName是否為空或值無效
if (fileNameString.Trim() == "")
{ return; }
//定義表格內資料的行數和列數
int rowscount = dgv.Rows.Count;
int colscount = dgv.Columns.Count;
//行數必須大於0
if (rowscount <= 0)
{
MessageBox.Show("沒有資料可供儲存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//列數必須大於0
if (colscount <= 0)
{
MessageBox.Show("沒有資料可供儲存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//行數不可以大於100000
if (rowscount > 100000)
{
MessageBox.Show("資料記錄數太多(最多不能超過100000條),不能儲存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//列數不可以大於255
if (colscount > 255)
{
MessageBox.Show("資料記錄行數太多,不能儲存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//驗證以fileNameString命名的檔案是否存在,如果存在刪除它
FileInfo file = new FileInfo(fileNameString);
if (file.Exists)
{
try
{
file.Delete();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "刪除失敗 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
#endregion
Microsoft.Office.Interop.Excel.Application objExcel = null;
Microsoft.Office.Interop.Excel.Workbook objWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet objsheet = null;
try
{
//申明物件
objExcel = new Microsoft.Office.Interop.Excel.Application();
objWorkbook = objExcel.Workbooks.Add(Missing.Value);
objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet;
//設定EXCEL不可見
objExcel.Visible = false;
//向Excel中寫入表格的表頭
int displayColumnsCount = 1;
for (int i = 0; i <= dgv.ColumnCount - 1; i++)
{
if (dgv.Columns[i].Visible == true && dgv.Columns[i].HeaderText.Trim() != "刪除" && dgv.Columns[i].HeaderText.Trim() != "")
{
objExcel.Cells[1, displayColumnsCount] = dgv.Columns[i].HeaderText.Trim();
displayColumnsCount++;
}
}
//設定進度條
tempProgressBar.Refresh();
tempProgressBar.Visible = true;
tempProgressBar.Minimum = 1;
tempProgressBar.Maximum = dgv.RowCount;
tempProgressBar.Step = 1;
//向Excel中逐行逐列寫入表格中的資料
for (int row = 0; row <= dgv.RowCount - 1; row++)
{
tempProgressBar.PerformStep();
displayColumnsCount = 1;
for (int col = 0; col < colscount; col++)
{
if (dgv.Columns[col].Visible == true && dgv.Columns[col].HeaderText != "刪除" && dgv.Columns[col].HeaderText.Trim() != "")
{
try
{
string Val = dgv.Rows[row].Cells[col].Value.ToString().Trim();
if (Val.Length > 8)
{
Val = "'" + Val;//加單引號
}
objExcel.Cells[row + 2, displayColumnsCount] = Val;
displayColumnsCount++;
}
catch (Exception)
{
}
}
}
}
//隱藏進度條
tempProgressBar.Visible = false;
//儲存檔案
objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
}
catch (Exception error)
{
MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
finally
{
//關閉Excel應用
if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
if (objExcel.Workbooks != null) objExcel.Workbooks.Close();
if (objExcel != null) objExcel.Quit();
objsheet = null;
objWorkbook = null;
objExcel = null;
}
MessageBox.Show(fileNameString + "匯出完畢! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
}
}
使用方式:
/// <summary>
/// 將資料傳遞給分頁
/// </summary>
/// <param name="ds">傳入表資料表集合</param>
private void setPage(DataSet ds)
{
wyyNavigator1.DsAll = ds;
wyyNavigator1.dataBand();
}
檔案地址:
連結:https://pan.baidu.com/s/1bzypbPcgdkCJScbH_uqzWA 密碼:irjd