我看到其它各大博客里面各位博主也有关于DataGridView自定义分页控件的文章。虽然功能能实现,但是我觉得一是自定义控件代码太复杂,小白容易看晕;二是分页查询语句过于复杂,小白更容易看晕。现在就来说一下流程:
1、创建数据库、数据表
2、编写分页查询存储过程语句
3、编写查询表记录个数存储过程语句
4、编写自定义控件
总的来说就以上三步,现在我们来细化一下。
创建数据库、数据表
此处就不多说了,自行创建即可。
例如我自己创建了一个测试表:
--创建数据表 CREATE TABLE [dbo].[T_test]( [id] [varchar](36) NOT NULL, [name] [nvarchar](50) NULL, [age] [int] NULL, [sex] [nvarchar](2) NULL, [address] [nvarchar](50) NULL, [job] [nvarchar](50) NULL, CONSTRAINT [PK_T_test] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] --插入数据 INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'273ff92e-0c60-4929-baaf-c53048e1b14a', N'张三', 23, N'男', N'济南市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'27d26321-767b-4760-855c-2dcb3a1d0e45', N'王鹏', 21, N'女', N'济南市', N'美工') INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'28022085-9aa2-4fac-8c5f-be8d4e129afb', N'陈豪', 25, N'男', N'泰安市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'3a7145bb-688f-4fa1-b8e9-ad167ddd5be2', N'郭富', 24, N'男', N'济南市', N'软件开发高级工程师') INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'4828099f-a56a-4fa6-86c0-7d8109b0c3b0', N'王志强', 25, N'男', N'泰安市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'593482c0-2610-4f50-8ff5-7e9b47031145', N'陈赫', 33, N'男', N'泰安市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'5c6351ef-6644-4948-82cc-d0f0e5b0d67e', N'陈斌', 29, N'女', N'济南市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'7063ac03-1057-4c09-946d-ed599c75eaf8', N'赵敏', 21, N'女', N'济南市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'724ce083-3370-47f1-a921-d31cbdc2c187', N'魏*栋', 26, N'女', N'济南市', N'临沂市') INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'744032d8-6906-42b7-aedb-e9215ea13962', N'小丽', 22, N'女', N'泰安市', N'UI设计师') INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'e67e4ea7-9a62-4869-8ca5-b30d45fc8ba4', N'马旭', 22, N'男', N'济南市', NULL) INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'edf7274c-cdad-4056-bd9a-27be06eb72f7', N'唐寒枫', 24, N'男', N'山东省临沂市', N'设计师') INSERT [dbo].[T_test] ([id], [name], [age], [sex], [address], [job]) VALUES (N'fee2a0dd-1d93-4ed6-ad9e-6d8daa044311', N'王伟', 26, N'男', N'泰安市', NULL)
编写分页查询存储过程语句
--分页查询存储过程 if(exists(select* from sys.procedures where name='p_splitpage'))--如果存储过程存在 drop proc p_splitpage --删除存储过程 go create proc p_splitpage(@pageSize varchar(50), @currentPage varchar(50),@tableName varchar(50))--创建存储过程,定义三个变量'每页显示的条数'、'当前页'、‘表名’ as begin declare @sqlcommand varchar(max) set @sqlcommand ='select top '+@pageSize+' * from (select ROW_NUMBER() over(order by id) as rowid ,* from '+@tableName+')as A where rowid > ('+@pageSize+')*(('+@currentPage+')-1)' exec(@sqlcommand ) end
测试:exec p_splitpage '10','1','T_test'
编写查询表记录个数存储过程语句
--查询表记录数 if(exists(select* from sys.procedures where name='p_queryTableRecordCount')) drop proc p_queryTableRecordCount --那么就删除这个存储过程 go CREATE proc p_queryTableRecordCount(@tablename varchar(20)) AS BEGIN declare @sqlcommand varchar(max) set @sqlcommand ='select count(*) as 总记录数 from '+@tablename exec(@sqlcommand ) END GO
测试:exec p_queryTableRecordCount 'T_test';
编写自定义控件
新建项目
添加用户控件类
绘制用户控件
这就是我们要绘制的用户控件,没进行美化操作,丑一点就丑一点吧,各位可自行美化处理。
编写代码
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.Data.SqlClient; using DataHelper; namespace SX_ControlLibrary { public partial class DataNavigator : UserControl { public DataNavigator() { InitializeComponent(); } #region 变量定义 private int sx_totalCount = 0;//总数据个数 private int sx_pageCount = 0;//总页数 private int sx_currentPageCount = 0;//当前页数据记录数 private int sx_currentPageIndex = 1;//当前页索引 private int sx_pageSize = 10;//每页分页大小 private int sx_yuShu = 0;//最后一页剩余个数 private DataGridView sx_dataGirdView = null; private string sx_tableName = "";//DataGridViewd要绑定的表名 private string sx_procSplitPageName = "";//DataGridViewd要绑定的分页存储过程名称 private string sx_procQueryTableRecordCountName = "";//DataGridViewd要绑定的数据个数查询存储过程名称 private bool sx_isAutoUpdateLabelTip = true;//获取或设置是否自动更新分页标签内容提示,默认为true #endregion #region 控件事件定义 //[Category("SX"), Description("【上一页,<<】点击事件")] //public event EventHandler lbForwardClick; //[Category("SX"), Description("【下一页,>>】点击事件")] //public event EventHandler lbNextClick; //[Category("SX"), Description("【最后一页,>>|】点击事件")] //public event EventHandler lbLastClick; //[Category("SX"), Description("【首页,|<<】点击事件")] //public event EventHandler lbFirstClick; //[Category("SX"), Description("【显示记录数】修改事件")] //public event EventHandler txtPageCountKeyPress; /// <summary> /// 上一页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbForward_Click(object sender, EventArgs e) { if (sx_currentPageIndex <= sx_pageCount && sx_currentPageIndex != 1) sx_currentPageIndex--; Sx_initDataGirdView(); if (Sx_IsAutoUpdateLabelTip) Sx_updateSplitPageLabelTip(); } /// <summary> /// 下一页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbNext_Click(object sender, EventArgs e) { if (sx_currentPageIndex < sx_pageCount && sx_currentPageIndex != sx_pageCount) sx_currentPageIndex++; Sx_initDataGirdView(); if (Sx_IsAutoUpdateLabelTip) Sx_updateSplitPageLabelTip(); } /// <summary> /// 最后一页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbLast_Click(object sender, EventArgs e) { sx_currentPageIndex = sx_pageCount; Sx_initDataGirdView(); } /// <summary> /// 首页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbFirst_Click(object sender, EventArgs e) { sx_currentPageIndex = 1; Sx_initDataGirdView(); } private void txtPageCount_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == ' ') { //TODO 判断处理 暂时不进行数据验证 sx_pageSize = Convert.ToInt32(txtPageCount.Text); calcPageInfo(); Sx_initDataGirdView(); } } #endregion #region 属性定义 /// <summary> /// 获取或设置是否自动更新分页标签内容提示,默认为true,false:不自动更新,可由开发者自行获取数据设置 /// </summary> [Category("SX"), Description("获取或设置是否自动更新分页标签内容提示,默认为true,false:不自动更新,可由开发者自行获取数据设置"), Browsable(true)] public bool Sx_IsAutoUpdateLabelTip { get { return sx_isAutoUpdateLabelTip; } set { sx_isAutoUpdateLabelTip = value; } } /// <summary> /// 获取或设置DataGridViewd要绑定的表名 /// </summary> [Category("SX"), Description("获取或设置DataGridViewd要绑定的表名"), Browsable(true)] public string Sx_tableName { get { return sx_tableName; } set { sx_tableName = value; } } /// <summary> /// 获取或设置DataGridViewd要绑定的分页存储过程名称 /// </summary> [Category("SX"), Description("获取或设置DataGridViewd要绑定的分页存储过程名称"), Browsable(true)] public string Sx_procSplitPageName { get { return sx_procSplitPageName; } set { sx_procSplitPageName = value; } } /// <summary> /// 获取或设置DataGridViewd要绑定的数据个数查询存储过程名称 /// </summary> [Category("SX"), Description("获取或设置DataGridViewd要绑定的数据个数查询存储过程名称"), Browsable(true)] public string Sx_procQueryTableRecordCountName { get { return sx_procQueryTableRecordCountName; } set { sx_procQueryTableRecordCountName = value; } } /// <summary> /// 获取或设置DataGridViewd对象 /// </summary> [Category("SX"), Description("获取或设置DataGridViewd对象"), Browsable(true)] public DataGridView Sx_DataGridView { get { return sx_dataGirdView; } set { sx_dataGirdView = value; } } /// <summary> /// 获取或设置分页提示标签内容 /// </summary> [Category("SX"), Description("获取或设置分页提示标签内容"), Browsable(true)] public string Sx_LbInfo { get { return lbInfo.Text; } set { lbInfo.Text = value.ToString(); } } /// <summary> /// 获取总数据个数控价对象 /// </summary> [Category("SX"), Description("总数据个数控价对象"), Browsable(false)] public TextBox Sx_TxtPageCount { get { return txtPageCount; } } /// <summary> /// 获取或设置总数据个数 /// </summary> [Category("SX_Field"), Description("获取或设置总数据个数"), Browsable(true)] public int Sx_TotalCount { get { return sx_totalCount; } set { sx_totalCount = value; } } /// <summary> /// 获取或设置总页数 /// </summary>获取或设置 [Category("SX_Field"), Description("获取或设置总页数"), Browsable(true)] public int Sx_PageCount { get { return sx_pageCount; } set { sx_pageCount = value; } } /// <summary> /// 获取或设置每页分页大小 /// </summary> [Category("SX_Field"), Description("获取或设置每页分页大小"), Browsable(true)] public int Sx_PageSize { get { return sx_pageSize; } set { sx_pageSize = value; txtPageCount.Text = value.ToString(); } } /// <summary> /// 获取或设置当前页数据记录数 /// </summary> [Category("SX_Field"), Description("获取或设置当前页数据记录数"), Browsable(true)] public int Sx_CurrentPageCount { get { return sx_currentPageCount; } set { sx_currentPageCount = value; } } /// <summary> /// 获取或设置当前页索引 /// </summary> [Category("SX_Field"), Description("获取或设置当前页索引"), Browsable(true)] public int Sx_CurrentPageIndex { get { return sx_currentPageIndex; } set { sx_currentPageIndex = value; } } /// <summary> /// 获取或设置最后一页剩余个数 /// </summary> [Category("SX_Field"), Description("获取或设置最后一页剩余个数"), Browsable(true)] public int Sx_YuShu { get { return sx_yuShu; } set { sx_yuShu = value; } } #endregion #region 方法 /// <summary> /// 调用存储过程(分页存储过程)初始化dataGirdView /// </summary> /// <param name="tableName">要绑定的表名</param> /// <param name="procSplitPageName">分页查询的存储过程名称:p_splitPage</param> /// <param name="procQueryTableRecordCountName">查询数据个数的存储过程名称:p_queryTableRecordCount</param> public void Sx_initDataGirdView() { if (Sx_tableName.Length == 0) { MessageBox.Show("initDataGirdView方法未指定表名!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { SqlParameter[] sp = new SqlParameter[] { new SqlParameter("@pageSize",sx_pageSize), new SqlParameter("@currentPage",sx_currentPageIndex), new SqlParameter("@tableName",Sx_tableName) }; sx_dataGirdView.DataSource = CommonDB.invokeProc_DataTable(Sx_procSplitPageName, sp); #region dataGridView相关属性设置【抛出,不在此设置】 //// 设置 dataGridView1 的第1列整列单元格为只读 //dataGirdView.Columns[0].ReadOnly = true; //// 设定包括Header和所有单元格的列宽自动调整 //dataGirdView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; //// 设定包括Header和所有单元格的行高自动调整 //dataGirdView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; #endregion //查询表记录数 Sx_queryDataCount(); calcPageInfo(); } } /// <summary> /// 调用存储过程查询表记录数 /// </summary> /// <param name="tableName">表名</param> /// <param name="p_queryTableRecordCountName">存储过程名称:p_queryTableRecordCount</param> private void Sx_queryDataCount() { if ((Sx_tableName != null && Sx_tableName.Trim().Length != 0) && (Sx_procQueryTableRecordCountName != null && Sx_procQueryTableRecordCountName.Trim().Length != 0)) { //查询表记录数 SqlParameter[] sp = new SqlParameter[] { new SqlParameter("@tableName", Sx_tableName) }; object flag = CommonDB.invokeProc_ExecuteScalar(Sx_procQueryTableRecordCountName, sp); sx_totalCount = Convert.ToInt32(flag); } else { MessageBox.Show("queryDataCount参数有误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void Sx_updateSplitPageLabelTip() { lbInfo.Text = "总共" + sx_pageCount + "页" + ",当前第:" + sx_currentPageIndex + "页,其中最后一页有" + sx_yuShu + "条数据"; } /// <summary> /// 计算页信息 /// </summary> /// <param name="totalCount">总记录数</param> /// <param name="pageSize">每页要显示的条数</param> private void calcPageInfo() { sx_pageCount = sx_totalCount / sx_pageSize; //取模 sx_yuShu = sx_totalCount % sx_pageSize;//取余 if (sx_yuShu > 0) { sx_pageCount++; } Console.WriteLine("页大小:" + sx_pageSize); Console.WriteLine("当前页索引:" + sx_currentPageIndex); Console.WriteLine("pageCount:" + sx_totalCount + " / " + sx_pageSize + "=" + sx_pageCount); Console.WriteLine("yuShu:" + sx_totalCount + " % " + sx_pageSize + "=" + sx_yuShu); Console.WriteLine("总共" + sx_pageCount + "页" + ",当前第:" + sx_currentPageIndex + "页,其中最后一页有" + sx_yuShu + "条数据"); if (Sx_IsAutoUpdateLabelTip) Sx_updateSplitPageLabelTip(); } #endregion } }
用到的相关类库:CommonDB.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.Data; using System.Reflection; namespace DataHelper { public class CommonDB { private static string connStr = "server=.;database=ERP_DB;Integrated security=true;Trusted_Connection=SSPI"; /// <summary> /// 准备执行一个命令 /// </summary> /// <param name="cmd">sql命令</param> /// <param name="conn">Sql连接</param> /// <param name="trans">Sql事务</param> /// <param name="cmdText">命令文本,例如:Select * from Products</param> /// <param name="cmdParms">执行命令的参数</param> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) { //判断连接的状态。如果是关闭状态,则打开 if (conn.State != ConnectionState.Open) conn.Open(); //cmd属性赋值 cmd.Connection = conn; cmd.CommandText = cmdText; //是否需要用到事务处理 if (trans != null) cmd.Transaction = trans; //cmd.CommandType = CommandType.Text; cmd.CommandType = cmdType; //添加cmd需要的存储过程参数 if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } /// <summary> /// 调用存储过程 /// </summary> /// <param name="procName">存储过程名称</param> /// <param name="commandParameters">存储过程参数</param> /// <returns>返回受影响的行数</returns> public static int invokeProc_NonQuery(string procName, params SqlParameter[] commandParameters) { using (SqlConnection conn = new SqlConnection(connStr)) { SqlCommand sqlCmd = new SqlCommand(); PrepareCommand(sqlCmd, conn, null, CommandType.StoredProcedure, procName, commandParameters); int flag = sqlCmd.ExecuteNonQuery(); sqlCmd.Parameters.Clear(); return flag; } } /// <summary> /// 调用存储过程 /// </summary> /// <param name="procName">存储过程名称</param> /// <param name="commandParameters">存储过程参数</param> /// <returns>返回DataTable对象</returns> public static DataTable invokeProc_DataTable(string procName, params SqlParameter[] commandParameters) { using (SqlConnection conn = new SqlConnection(connStr)) { SqlCommand sqlCmd = new SqlCommand(); PrepareCommand(sqlCmd, conn, null, CommandType.StoredProcedure, procName, commandParameters); SqlDataAdapter da = new SqlDataAdapter(sqlCmd); DataTable dt = new DataTable(); try { //填充ds da.Fill(dt); // 清除cmd的参数集合 sqlCmd.Parameters.Clear(); //返回ds return dt; } catch (Exception ex) { LogLib.LogHelper.ERROR(ex); //关闭连接,抛出异常 conn.Close(); throw; } } } /// <summary> /// 调用存储过程。用指定的数据库连接执行一个命令并返回一个数据集的第一列 /// </summary> /// <param name="procName"></param> /// <param name="commandParameters"></param> /// <returns>返回一个数据集的第一列</returns> public static object invokeProc_ExecuteScalar(string procName, params SqlParameter[] commandParameters) { using (SqlConnection conn = new SqlConnection(connStr)) { SqlCommand sqlCmd = new SqlCommand(); PrepareCommand(sqlCmd, conn, null, CommandType.StoredProcedure, procName, commandParameters); object flag = sqlCmd.ExecuteScalar(); sqlCmd.Parameters.Clear(); return flag; } } } }
调用
新建一个winform窗体应用程序,拖入一个DataGirdView控件和刚才自定义控件,如下
代码:
using DataHelper; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TestProjrct { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { //指定控件对象 dataNavigator1.Sx_DataGridView = dataGridView1; //可以在代码中设置dataGirdView控件属性,也可以在【属性】窗格设置 //dataNavigator1.Sx_tableName = "T_test"; //dataNavigator1.Sx_procQueryTableRecordCountName = "p_queryTableRecordCount"; //dataNavigator1.Sx_procSplitPageName = "p_splitPage"; //调用控件方法,绑定数据 dataNavigator1.Sx_initDataGirdView(); // 设置 dataGridView1 的第1列整列单元格为只读 dataNavigator1.Sx_DataGridView.Columns[0].ReadOnly = true; // 设定包括Header和所有单元格的列宽自动调整 dataNavigator1.Sx_DataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; // 设定包括Header和所有单元格的行高自动调整 dataNavigator1.Sx_DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; } } }
可以看到,最终使用的时候代码很少,很简洁。只要创建好数据表以及相关存储过程(建议使用以上sql脚本用的存储过程默认名称,当然可以自定义)。
以上代码关键点有两个
一是:
dataNavigator1.Sx_DataGridView = dataGridView1;
二是设置参数进行数据绑定:
//可以在代码中设置dataGirdView控件属性,也可以在【属性】窗格设置 //dataNavigator1.Sx_tableName = "T_test"; //dataNavigator1.Sx_procQueryTableRecordCountName = "p_queryTableRecordCount"; //dataNavigator1.Sx_procSplitPageName = "p_splitPage";
dataNavigator1.Sx_initDataGirdView();
此处我在属性窗格进行设置的,如图:
当然可以代码设置,只需要将上面注释的代码(29~31行)打开即可。
37~42行进行相关特性设置,这个根据需要设置,非必须。
说明:
自定义控件的属性和相关方法都是以“Sx_”开头,便于查找,另外,相关注释说明也相对比较完善。
运行效果:
注意,以上“共:X条数据”没有动态更新,只要将属性Sx_IsAutoUpdateLabelTip改为true即可,代码设置也可以,属性表中设置也可以。改后: