如何在WinForm中对DataGrid进行分页显示

Winform/Csharp中使用定时器+分页算法实现DataGridView自动分页显示(模拟大屏切换效果) 在上面讲了设置DataGridView的样式设置以及定时器的使用之后,怎么利用定时器实现DataGridView自动分页显示。 阅读详情

       在网上大多数对DataGrid进行分页的例子都是Asp.net环境下的,其实在WinForm中也很简单。以下就是简单举一个例子。

 

       首先,需要定义一个数据库存储过程,用来获得指定页的数据记录,大致的数据结构和存储过程如下(在SQL Server 2000下):

字段名

类型

备注

EmployeeID

Int

自增字段,主键

EmployeeName

Varchar(20)

 

Salary

Int

 

CellPhone

Varchar(20)

 

EmailAddress

Varchar(20)

 

 

存储过程为:

CREATE PROCEDURE GetEmployees @EmployeeNum int, @StartNO int, @@TotalCount INT OUTPUT, @@RealNum INT OUTPUT AS

-- Get employees from DB through the specific number and the start position

DECLARE @PreRecCount VARCHAR( 10 )

DECLARE @CurRecCount VARCHAR( 10 )

 

SELECT @@TotalCount = COUNT(*) FROM EmployeeInfo

 

IF @@TotalCount > ( @StartNO + 1 ) * @EmployeeNum

    SET @@RealNum = @EmployeeNum

ELSE

    SET @@RealNum = @@TotalCount - @StartNO * @EmployeeNum

 

-- Get employees by the computed number

SET @CurRecCount = CAST( @StartNO * @EmployeeNum + @@RealNum AS VARCHAR( 10 ) )

IF @STARTNO = 0

   EXEC( 'SELECT TOP ' + @CurRecCount + ' * FROM EmployeeInfo ORDER BY EmployeeID ASC' )

ELSE

   BEGIN

         SET @PreRecCount = CAST( @StartNO * @EmployeeNum AS VARCHAR( 10 ) )

         EXEC( 'SELECT TOP ' + @CurRecCount + ' * FROM EmployeeInfo WHERE EmployeeID NOT IN '

                   + '(SELECT TOP ' + @PreRecCount + ' EmployeeID FROM EmployeeInfo ORDER BY EmployeeID ASC) '

                   + 'ORDER BY EmployeeID ASC'

                   )

   END

GO

 

然后就是调用存储过程来进行显示,比较完整的源代码如下:

//------------------------ Multi Page Demo ------------------------------------

//-----------------------------------------------------------------------------

//---File:frmMultiPagesDemo.cs

//---Description:The main form file to show how to use pages in datagrid

//---Author:Knight

//---Date:Mar.23, 2006

//-----------------------------------------------------------------------------

//-----------------------{ Multi Page Demo }-----------------------------------

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Data.SqlClient;

 

namespace CSDataGrid

{

    /// <summary>

    /// Summary description for frmMultiPages.

    /// </summary>

    public class frmMultiPages : System.Windows.Forms.Form

    {

        private System.Windows.Forms.Label lblPageInfo;

        private System.Windows.Forms.Button btnPrevious;

        private System.Windows.Forms.Button btnNext;

 

        protected SqlConnection sqlConn = new SqlConnection();

        protected SqlDataAdapter sqlDAdapter = null;

        protected DataSet sqlRecordSet = null;

 

        private int nCurPageNum = 0;

        private const int REC_NUM_PER_PAGE = 3;

        private int nTotalCount;

        private int nRealNum;

        private int nTotalPage;

 

        private System.Windows.Forms.DataGrid dtgUserInfo;

 

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.Container components = null;

 

        public frmMultiPages()

        {

            //

            // Required for Windows Form Designer support

            //

            InitializeComponent();

 

            //

            // TODO: Add any constructor code after InitializeComponent call

            //

        }

 

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        protected override void Dispose( bool disposing )

        {

            if( disposing )

            {

                if(components != null)

                {

                    components.Dispose();

                }

            }

            base.Dispose( disposing );

        }

 

        #region Windows Form Designer generated code

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.dtgUserInfo = new System.Windows.Forms.DataGrid();

            this.lblPageInfo = new System.Windows.Forms.Label();

            this.btnPrevious = new System.Windows.Forms.Button();

            this.btnNext = new System.Windows.Forms.Button();

            ((System.ComponentModel.ISupportInitialize)(this.dtgUserInfo)).BeginInit();

            this.SuspendLayout();

            //

            // dtgUserInfo

            //

            this.dtgUserInfo.DataMember = "";

            this.dtgUserInfo.HeaderForeColor = System.Drawing.SystemColors.ControlText;

            this.dtgUserInfo.Location = new System.Drawing.Point(16, 16);

            this.dtgUserInfo.Name = "dtgUserInfo";

            this.dtgUserInfo.Size = new System.Drawing.Size(552, 416);

            this.dtgUserInfo.TabIndex = 0;

            //

            // lblPageInfo

            //

            this.lblPageInfo.AutoSize = true;

            this.lblPageInfo.Location = new System.Drawing.Point(16, 440);

            this.lblPageInfo.Name = "lblPageInfo";

            this.lblPageInfo.Size = new System.Drawing.Size(83, 16);

            this.lblPageInfo.TabIndex = 1;

            this.lblPageInfo.Text = "{0} of {1} Pages";

            //

            // btnPrevious

            //

            this.btnPrevious.Location = new System.Drawing.Point(408, 440);

            this.btnPrevious.Name = "btnPrevious";

            this.btnPrevious.TabIndex = 2;

            this.btnPrevious.Text = "Previous";

            this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);

            //

            // btnNext

            //

            this.btnNext.Location = new System.Drawing.Point(488, 440);

            this.btnNext.Name = "btnNext";

            this.btnNext.TabIndex = 3;

            this.btnNext.Text = "Next";

            this.btnNext.Click += new System.EventHandler(this.btnNext_Click);

            //

            // frmMultiPages

            //

            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

            this.ClientSize = new System.Drawing.Size(584, 469);

            this.Controls.Add(this.btnNext);

            this.Controls.Add(this.btnPrevious);

            this.Controls.Add(this.lblPageInfo);

            this.Controls.Add(this.dtgUserInfo);

            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

            this.MaximizeBox = false;

            this.Name = "frmMultiPages";

            this.Text = "Multi Pages In DataGrid";

            this.Load += new System.EventHandler(this.frmMultiPages_Load);

            ((System.ComponentModel.ISupportInitialize)(this.dtgUserInfo)).EndInit();

            this.ResumeLayout(false);

 

        }

        #endregion

 

        private void frmMultiPages_Load(object sender, System.EventArgs e)

        {

            //Set connection string

            sqlConn.ConnectionString = yourconnectionstring;

 

            //Connect to DB

            if( ConnectDB() )

            {

                //Bind data to datagrid

                BindData();

            }

       

        }

 

        /// <summary>

        /// Connect to DB

        /// </summary>

        /// <returns>If connected, return True; else return False</returns>

        private bool ConnectDB()

        {

            //Check current connection's state

            try

            {

                if(     sqlConn.State == ConnectionState.Closed

                    ||  sqlConn.State == ConnectionState.Broken )

                {

                    //Connection is not available

                    sqlConn.Close();

                }

                else

                    //Connection is available

                    return true;

            }

            catch{};

 

            //Re-connect

            try

            {

                sqlConn.Open();

            }

            catch(SqlException e)

            {

                //Sql's exception

                MessageBox.Show( e.Message );

            }

            catch(Exception e)

            {

                //Other exception

                MessageBox.Show( e.Message );

            }

 

            if(     sqlConn.State == ConnectionState.Closed

                ||  sqlConn.State == ConnectionState.Broken )

                //Connection is not available

                return false;

            else

                //Connection is available

                return true;

        }

 

        private void AddDGStyle()

        {

            DataGridTableStyle ts1 = new DataGridTableStyle();

 

            //specify the table from dataset (required step)

            ts1.MappingName = "EmployeeInfo";

            PropertyDescriptorCollection pdc = this.BindingContext

                [sqlRecordSet, "EmployeeInfo"].GetItemProperties();

 

            DataGridColumnStyle TextCol = new DataGridTextBoxColumn( pdc["EmployeeID"], "i" );

            TextCol.MappingName = "EmployeeID";

            TextCol.HeaderText = "EmployeeID";

            TextCol.Width = 0;

            TextCol.ReadOnly = true;

            ts1.GridColumnStyles.Add(TextCol);

 

            TextCol = new DataGridTextBoxColumn();

            TextCol.MappingName = "EmployeeName";

            TextCol.HeaderText = "Employee Name";

            TextCol.Width = 100;

            ts1.GridColumnStyles.Add(TextCol);

           

            TextCol = new DataGridTextBoxColumn( pdc["Salary"], "i" );

            TextCol.MappingName = "Salary";

            TextCol.HeaderText = "Salary";

            TextCol.Width = 80;

            ts1.GridColumnStyles.Add(TextCol);

           

            TextCol = new DataGridTextBoxColumn();

            TextCol.MappingName = "CellPhone";

            TextCol.HeaderText = "Cell Phone";

            TextCol.Width = 80;

            ts1.GridColumnStyles.Add(TextCol);

 

            TextCol = new DataGridTextBoxColumn();

            TextCol.MappingName = "EmailAddress";

            TextCol.HeaderText = "Email Address";

            TextCol.Width = 100;

            ts1.GridColumnStyles.Add(TextCol);

 

            dtgUserInfo.TableStyles.Add(ts1);

 

        }

 

        private void GetEmployeeData()

        {

            sqlDAdapter = new SqlDataAdapter( );

            SqlCommand sqlComm = new SqlCommand();

            sqlComm.Connection = sqlConn;

 

            sqlComm.CommandText = "GetEmployees";

            sqlComm.CommandType = CommandType.StoredProcedure;

            sqlComm.Parameters.Add ( "@EmployeeNum", REC_NUM_PER_PAGE );

            sqlComm.Parameters.Add ( "@StartNO", nCurPageNum );

            SqlParameter sqlPar = sqlComm.Parameters.Add ( "@@TotalCount", SqlDbType.Int );

            sqlPar.Direction = ParameterDirection.Output;

            sqlPar = sqlComm.Parameters.Add ( "@@RealNum", SqlDbType.Int );

            sqlPar.Direction = ParameterDirection.Output;

 

            sqlDAdapter.SelectCommand = sqlComm;

 

            //Fill dataset

            sqlRecordSet = new DataSet();

            sqlDAdapter.Fill( sqlRecordSet, "EmployeeInfo" );

            nTotalCount = Convert.ToInt32( sqlComm.Parameters["@@TotalCount"].Value.ToString() );

            nRealNum = Convert.ToInt32( sqlComm.Parameters["@@RealNum"].Value.ToString() );

           

            sqlComm.Dispose();

 

            nTotalPage = nTotalCount - nTotalCount % REC_NUM_PER_PAGE;

            nTotalPage /= REC_NUM_PER_PAGE;

            nTotalPage++;

 

            lblPageInfo.Text = string.Format( "{0} of {1} pages", nCurPageNum + 1, nTotalPage );

            if( nCurPageNum + 1 >= nTotalPage )

                btnNext.Enabled = false;

            else

                btnNext.Enabled = true;

 

            if( nCurPageNum == 0 )

                btnPrevious.Enabled = false;

            else

                btnPrevious.Enabled = true;

               

        }

 

        private void BindData()

        {

            GetEmployeeData();

 

            //Bind datagrid with dataset

            dtgUserInfo.SetDataBinding( sqlRecordSet, "EmployeeInfo");

 

            //Add datagrid style

            AddDGStyle();

        }

 

        private void ReBindData()

        {

            GetEmployeeData();

 

            //Bind datagrid with dataset

            dtgUserInfo.SetDataBinding( sqlRecordSet, "EmployeeInfo");

        }

 

        private void btnPrevious_Click(object sender, System.EventArgs e)

        {

            nCurPageNum--;

            sqlRecordSet.Tables["EmployeeInfo"].Rows.Clear();

            ReBindData();

        }

 

        private void btnNext_Click(object sender, System.EventArgs e)

        {

            nCurPageNum++;

            sqlRecordSet.Tables["EmployeeInfo"].Rows.Clear();

            ReBindData();

        }

 

    }

}

 

WinForm-分页显示-SQlite.rar 基于winform,列举datagrid中的元素,指定每页显示元素数量,并且连续显示每页数据编号,动态显示,实现数据每页显示 立即下载

相关推荐

避坑指南:RFSoC数据转换器多片同步配置的7个致命错误

本文深入剖析了在配置RFSoC多片同步功能时,工程师最常遇到的七个致命错误。从Tile 0的强制启用、时钟域与SYSREF时序,到跨代器件兼容性、电源序列以及动态重配置的陷阱,文章结合实战经验,提供了从原理到调试的完整RF数据转换器配置指南,旨在帮助开发者高效构建相位一致的大规模射频采样系统。

weixin_28452161的博客 536

winform dateGrid实现分页

winform dataGrid进行分页

weixin_42992927的博客 426

手把手教你用EG2153搭建开关电源:SOP-8封装驱动芯片的5个设计技巧

本文详细介绍了使用EG2153自振荡半桥驱动芯片搭建开关电源的五个核心设计技巧。内容涵盖从深入理解芯片工作机制、频率编程计算误区、SOP-8封装的热管理方案,到死区时间评估与外部保护电路设计,以及实战调试与故障排查指南,旨在帮助工程师实现稳定可靠的小功率电源设计。

weixin_29200485的博客 381

WinForm轻松实现自定义分页 (转载)

转载至http://xuzhihong1987.blog.163.com/blog/static/267315872011315114240140/ 以前都是做web开发,最近接触了下WinForm,发现WinForm分页控件好像都没有,网上搜索了一下,发现有很多网友写的分页控件,分页效果应该都能实现吧,只是其风格都不是很符合我想要的。做web的时候,我习惯了Extjs的Grid分页效...

aiquan6271的博客 489

PCL 平面点云的凹多边形边界提取【2025最新版】

平面点云的凹多边形边界提取及边界轮廓线绘制。博客长期更新,本文最近更新时间为:2025年1月6日。

点云侠的博客 7189

winform控件 datagridview分页功能

【代码】winform控件 datagridview分页功能。

Pei_hua100的专栏 2859

【Mode】微带传输线阻抗

微带线,英文名称为 (Microstrip) 是一种常见的平面传输线,主要用于传输微波频率信号(通常在射频和微波电路重中使用)。

u011699626的博客 246

如何在WinForm中对DataGrid进行分页显示收藏

在网上大多数对DataGrid进行分页的例子都是Asp.net环境下的,其实在WinForm中也很简单。以下就是简单举一个例子。        首先,需要定义一个数据库存储过程,用来获得指定页的数据记录,大致的数据结构和存储过程如下(在SQL Server 2000下):字段名类型备注EmployeeIDInt自增字段,主

mygoda的专栏 491

大数据知识面试题-Hadoop(2022版)

序列号 内容 链接 1 大数据知识面试题-通用(2022版) 待续… 2 大数据知识面试题-Hadoop(2022版) 待续… 3 大数据知识面试题-MapReduce和yarn(2022版) 待续… 4 大数据知识面试题-Zookeepr (2022版) 待续… 5 大数据知识面试题-Hive (2022版) 待续… 6 大数据知识面试题-Flume(2022版) 待续… 7 大数据知识面试题-Hbase(2022版) 待续… 8 大数据知识面试题-sqoop(....

拉格朗日的学习笔记 1万+

静态时序分析—门控时钟检查(clock gating check)

clock gating check的条件与类型

m0_61544122的博客 9632

基于多传感器融合的智身四足机器狗楼梯环境SLAM系统设计与实现

本文设计了一种基于多传感器融合的四足机器狗楼梯环境SLAM系统。系统采用Jetson Orin NX为主控制器,集成RealSense D435i深度相机和Livox Mid360激光雷达,在ROS2框架下实现平面定位精度<5cm、楼梯环境下导航不漂移的目标。通过多层次传感器融合策略、运动学约束优化和状态切换机制,解决了楼梯环境下的定位累积误差问题,实现了平面与楼梯环境的自动识别切换及精度复位功能。硬件设计注重传感器布局优化和精确标定,软件架构采用分层设计,确保实时性能。该系统为四足机器人在复杂地形中

huanghm88的专栏 257

关于在winform下DataGrid分页代码

关于在winform下DataGrid分页代码 最近头头要我们用DataGrid显示数据的时候一条一条的显示,当点击了某按钮时,下条记录就出现,也就是一次只显示一条记录,~于是我就想到了用DataGrid分页,当然我们在开发中也遇到了很多问题,特别是细节上的~在这里我要特别感谢我的朋友reficul和Oscar给了我不少帮助~ -------------------------代码----...

weixin_34267123的博客 133

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

winform 分页控件

前阵子写了一个winform的数据库管理程序,用一个dataGrid显示数据库表中的所有内容,后来发现当数据库中的条目增多的时候,程序运行速度明显下降,系统占用内存也很大,决定对dataGrid做个分页,每次只取出要显示页的内容。程序很简单,用的时候需要提供pageCount(页数),pageShow(显示的页数),currPage(当前页号)lblPageCount.Text = "共" + pageCount + "页";if (ctlObj.Text.IndexOf("共") >= 0)

biyusr的专栏 596

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

C# WinForm开发系列 - DataGrid/DataGridView(转)

在WinForm开发中,DataGrid/DataGridView被广泛使用于绑定数据库中数据进行呈现.整理一些关于DataGrid/DataGridView使用的文章,涉及DataGrid/DataGridView基本功能,自定义绘制控件,数据导入/导出(Excel),打印等. 1.新数据网格简介(DataGridView) 2.自定义DataGridView外观 3.怎样让W

csdn_aspnet的专栏,请点击博客主页右上角三个点中的私信联系 1999

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

WinForm 分页控件

  这次把我写的一个分页控件贴上来。前阵子写了一个winform的数据库管理程序,用一个dataGrid显示数据库表中的所有内容,后来发现当数据库中的条目增多的时候,程序运行速度明显下降,系统占用内存也很大,决定对dataGrid做个分页,每次只取出要显示页的内容。上网搜了一下,没有找到我需要的,于是自己写了一个分页控件。程序很简单,用的时候需要提供pageCount(页数),page

记事本 1436

存储过程返回值问题

1。/// /// 存储过程执行函数/// /// 存储过程名/// 参数信息集/// 需返回的参数名数组/// 存有返回值的HashTablepublic void ExecStoredProcedure(string strSpName,Hashtable ht,string[] strParameterArray){SqlCommand comm = new SqlCommand(strSp

2001
上一篇: 如何在程序中互斥的操作数据库
下一篇: 如何用C#添加Access数据源
Knight94
博客等级 码龄25年 1013粉丝 87原创
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址