惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
H
Help Net Security
小众软件
小众软件
N
Netflix TechBlog - Medium
C
Check Point Blog
量子位
Last Week in AI
Last Week in AI
GbyAI
GbyAI
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
D
DataBreaches.Net
Project Zero
Project Zero
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
Security Latest
Security Latest
Cisco Talos Blog
Cisco Talos Blog
Recorded Future
Recorded Future
I
Intezer
L
Lohrmann on Cybersecurity
Cyberwarzone
Cyberwarzone
博客园_首页
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LangChain Blog
P
Palo Alto Networks Blog
V
V2EX
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
The Exploit Database - CXSecurity.com
The Hacker News
The Hacker News
Blog — PlanetScale
Blog — PlanetScale
G
GRAHAM CLULEY
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
The Register - Security
The Register - Security
L
LINUX DO - 热门话题
P
Privacy & Cybersecurity Law Blog
Scott Helme
Scott Helme
F
Full Disclosure
博客园 - 司徒正美
Recent Announcements
Recent Announcements
IT之家
IT之家
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Attack and Defense Labs
Attack and Defense Labs
Cloudbric
Cloudbric
Help Net Security
Help Net Security
The Last Watchdog
The Last Watchdog

博客园 - 恭喜发财

android 电话状态的监听(来电和去电) (转)Xml DML - 恭喜发财 - 博客园 (转)sql:variable() binding and modify method of xquery: insert XML DML 在WinForm中控制GIF动画的启停的一种方法(转) SQL Server Backup file in standard Zip format Working with binary large objects (BLOBs) c# 得到局域网中可用SqlServer服务器列表(转) C#实现UDP协议(转) 健康大讲堂—凡膳皆药 寓医于食 ReportView(RDSL)参考资料 How To Print Using Custom Page Sizes on Windows NT and Windows 2000(VB6) 汇总c#.net常用函数和方法集 在多线程中如何调用Winform 使用C#在进度条中显示复制文件的进度(转) c#将大文件读取或写入到数据库(带进度条的源码)(转) 写C#自定义控件的心得 Finalize(析构函数)、Dispose、Close 的区别与使用 如何用C#做一个类似于桌面插件的程序(转) c#连接各类数据库大全
如何在WinForm中对DataGrid进行分页显示(转)
恭喜发财 · 2008-06-17 · via 博客园 - 恭喜发财

在网上大多数对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();

        }

    }

}