winform中DataGridView实现分页功能

合集下载

C#winform分页查询的实现示例

C#winform分页查询的实现示例

C#winform分页查询的实现⽰例1、功能需求本实例将通过c# winform实现简单的分页功能,需要的基础知识有SQL语句,c#语⾔基础以及c# winform的⼀些简单知识。

2、界⾯设计这是⼀个简单的分页查询的界⾯,可以输⼊任意字段进⾏查询,这四个字段在数据准备会提到,整体界⾯如图1所⽰。

图1中间显⽰是⼀个DataGridView,编辑好列和id,SortMode选择Automatic,意思是所有列⾃动铺满DataGridView,如图2所⽰。

图23、数据准备本实例涉及到删查改,因此要有数据表以及对数据表进⾏操作的代码。

数据库表⾮常简单,如图3所⽰,分别有对应四个字段。

图3later_back模型类对应数据库操作类代码如下:using MySql.Data.MySqlClient;using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using WindowsFormsApp1.Bean;namespace WindowsFormsApp1.SqlHelper{class LaterBackHelper{public LaterBackHelper(){}public void insert(LaterBack laterBack){string sql = "insert into later_back(dormitory_id,student_no,time,reason) values('" + laterBack.Dormitory_id + "','" + laterBack.Student_no + "'," + "'" + laterBack.Time + "'," + "'" + laterBack.Reason + "')";try{int iRet = SqlHelperBase.ExecuteSql(sql);if (iRet > 0){MessageBox.Show("新增成功", "系统提⽰");}else{MessageBox.Show("新增失败", "系统提⽰");}}catch (Exception){throw;}}public int update(LaterBack laterBack){string sql = "update later_back set reason='" + laterBack.Reason + "' where student_no= '" + laterBack.Student_no + "' and"+ " time = '" + laterBack.Time + "' and " + " dormitory_id= '" + laterBack.Dormitory_id + "'";try{int iRet = SqlHelperBase.ExecuteSql(sql);//这⾥返回的是受影响的⾏数,为int值。

C#DataGridView分页显示代码详解

C#DataGridView分页显示代码详解
this.dataGridView1.DataSource = gettb(selectsql ,start,count,"table")‘;//绑定 DataGridView
} }
上边红色部分获取总行数是调用的数据操作层里的 getds 方法返回一个数据集, 类和方法如下:
class DBExecute { string G_str_connectionString = @"Data
/// 第一页 private void toolStripButton2_Click(object sender, EventArgs e) {
if (pageall > 1) {
start = 0; page = 1; tslPage.Text = page.ToString(); this.dataGridView1.DataSource = gettb(selectsql ,start,count,"table")‘;//绑定 DataGridView } }
C#DataGridView 分页显示代码详解
DBClass.DBExecute dbexecute = new DBExecute();
string connectionString = @"Data Source=ServerName;Database=DatabaseName;integrated security=true";
// 上一页 private void toolStripButton3_Click(object sender, EventArgs e) {
if (page >1) {
page--; start -= 20; tslPage.Text = page.ToString();

winform中DataGridView实现分页功能

winform中DataGridView实现分页功能

winform中DataGridView实现分页功能转载⾄以前都是做web开发,最近接触了下WinForm,发现WinForm分页控件好像都没有,⽹上搜索了⼀下,发现有很多⽹友写的分页控件,分页效果应该都能实现吧,只是其风格都不是很符合我想要的。

做web的时候,我习惯了Extjs的Grid分页效果,所以也想在WinForm中做个类似的效果,所以咬咬⽛,做个⼭寨版本的吧,虽然⾃⼰写费时费⼒,在项⽬进度考虑中不是很可取,但是还是特别想⼭寨⼀回,做⾃⼰喜欢的风格。

按照惯例,还是先看看实现效果图吧(有图有真像,才好继续下⽂呀)应⽤效果:(效果有点难看,因为我是刚装的xp系统,还是经典主题,如果换成Win7系统或其他主题,效果还是会很不错的)我们要做的就是上图显⽰的⼀个⾃定义控件,这个效果参考⾃我做web开发使⽤的Extjs之Grid的分页效果(如下图)Extjs的动画效果我们暂时就不实现了,这⾥只做个外观看起来想像即可,完全⼀样就脱离“⼭寨”概念了,总要⽐⼈家差点吧,谁让咱是模仿呢!⾔归正传,我们现在就看看具体怎么实现吧:第⼀步:先布局注:我们创建的是⽤户⾃定义控件,⽽不是WinForm窗体就是先做出个显⽰效果,这个布局很简单,在这就不多说,重点就是“⾸页、前⼀页、后⼀页、末页”图标,每个图标分两种,⼀是能点击的⾼亮效果,⼀个是灰⾊不不能点击。

以下是套图:(⼤家如果不喜欢,可以去做成⾃⼰喜欢的风格图⽚)第⼆步:编写分页代码布局好了,那么第⼆步我们就要代码实现正确显⽰⽂字信息,分页事件,每页条数选择事件,公开属性和事件。

以下是完整代码:1///<summary>2///声明委托3///</summary>4///<param name="e"></param>5public delegate void EventPagingHandler (EventArgs e);6public partial class Paging : UserControl7 {8public Paging()9 {10 InitializeComponent();11 }12public event EventPagingHandler EventPaging;13#region公开属性14private int _pageSize = 50;15///<summary>16///每页显⽰记录数(默认50)17///</summary>18public int PageSize19 {20get21 {22return _pageSize;23 }24set25 {26if (value > 0)27 {28 _pageSize = value;29 }30else31 {32 _pageSize = 50;33 }boPageSize.Text = _pageSize.ToString();35 }36 }37private int _currentPage = 1;38///<summary>39///当前页40///</summary>41public int CurrentPage42 {43get44 {45return _currentPage;46 }47set48 {49if (value > 0)50 {51 _currentPage = value;52 }53else54 {55 _currentPage = 1;56 }5758 }59 }60private int _totalCount = 0;61///<summary>62///总记录数63///</summary>64public int TotalCount65 {66get67 {68return _totalCount;69 }70set71 {72if (value >= 0)73 {74 _totalCount = value;75 }76else77 {78 _totalCount = 0;79 }80this.lblTotalCount.Text = this._totalCount.ToString();81 CalculatePageCount();82this.lblRecordRegion.Text = GetRecordRegion();83 }84 }8586private int _pageCount = 0;87///<summary>88///页数89///</summary>90public int PageCount91 {92get93 {94return _pageCount;95 }96set97 {98if (value >= 0)99 {100 _pageCount = value;101 }102else103 {104 _pageCount = 0;105 }106this.lblPageCount.Text = _pageCount + "";107 }108 }109#endregion110111///<summary>112///计算页数113///</summary>114private void CalculatePageCount()115 {116if (this.TotalCount > 0)117 {118this.PageCount = Convert.ToInt32 (Math.Ceiling (Convert.ToDouble (this.TotalCount) / Convert.ToDouble (this.PageSize) ) ); 119 }120else121 {122this.PageCount = 0;123 }124 }125126///<summary>127///获取显⽰记录区间(格式如:1-50)128///</summary>129///<returns></returns>130private string GetRecordRegion()131 {132if (this.PageCount == 1) //只有⼀页133 {134return"1-" + this.TotalCount.ToString();135 }136else//有多页137 {138if (this.CurrentPage == 1) //当前显⽰为第⼀页139 {140return"1-" + this.PageSize;141 }142else if (this.CurrentPage == this.PageCount) //当前显⽰为最后⼀页143 {144return ( (this.CurrentPage - 1) * this.PageSize + 1) + "-" + this.TotalCount;145 }146else//中间页147 {148return ( (this.CurrentPage - 1) * this.PageSize + 1) + "-" + this.CurrentPage * this.PageSize;149 }150 }151 }152153///<summary>154///数据绑定155///</summary>156public void Bind()157 {158if (this.EventPaging != null)159 {160this.EventPaging (new EventArgs() );161 }162if (this.CurrentPage > this.PageCount)163 {164this.CurrentPage = this.PageCount;165 }166this.txtBoxCurPage.Text = this.CurrentPage + "";167this.lblTotalCount.Text = this.TotalCount + "";168this.lblPageCount.Text = this.PageCount + "";169this.lblRecordRegion.Text = GetRecordRegion();170if (this.CurrentPage == 1)171 {172this.btnFirst.Enabled = false;173this.btnPrev.Enabled = false;174this.btnFirst.Image = global::CHVM.Properties.Resources.page_first_disabled; 175this.btnPrev.Image = global::CHVM.Properties.Resources.page_prev_disabled; 176 }177else178 {179this.btnFirst.Enabled = true;180this.btnPrev.Enabled = true;181this.btnFirst.Image = global::CHVM.Properties.Resources.page_first;182this.btnPrev.Image = global::CHVM.Properties.Resources.page_prev;183 }184if (this.CurrentPage == this.PageCount)185 {186this.btnNext.Enabled = false;187this.btnLast.Enabled = false;188this.btnNext.Image = global::CHVM.Properties.Resources.page_next_disabled; 189this.btnLast.Image = global::CHVM.Properties.Resources.page_last_disabled; 190 }191else192 {193this.btnNext.Enabled = true;194this.btnLast.Enabled = true;195this.btnNext.Image = global::CHVM.Properties.Resources.page_next;196this.btnLast.Image = global::CHVM.Properties.Resources.page_last;197 }198if (this.TotalCount == 0)199 {200this.btnFirst.Enabled = false;201this.btnPrev.Enabled = false;202this.btnNext.Enabled = false;203this.btnLast.Enabled = false;204this.btnFirst.Image = global::CHVM.Properties.Resources.page_first_disabled; 205this.btnPrev.Image = global::CHVM.Properties.Resources.page_prev_disabled; 206this.btnNext.Image = global::CHVM.Properties.Resources.page_next_disabled; 207this.btnLast.Image = global::CHVM.Properties.Resources.page_last_disabled; 208 }209 }210211private void btnFirst_Click (object sender, EventArgs e)212 {213this.CurrentPage = 1;214this.Bind();215 }216217private void btnPrev_Click (object sender, EventArgs e)218 {219this.CurrentPage -= 1;220this.Bind();221 }222223private void btnNext_Click (object sender, EventArgs e)224 {225this.CurrentPage += 1;226this.Bind();227 }228229private void btnLast_Click (object sender, EventArgs e)230 {231this.CurrentPage = this.PageCount;232this.Bind();233 }234235///<summary>236///改变每页条数237///</summary>238///<param name="sender"></param>239///<param name="e"></param>240private void comboPageSize_SelectedIndexChanged (object sender, EventArgs e) 241 {242this.PageSize = Convert.ToInt32 (comboPageSize.Text);243this.Bind();244 }245 }246247这⾥重点提两点:⼀是图⽚切换:248this.btnFirst.Image = global::CHVM.Properties.Resources.page_first_disabled;249 Image对象是在Properties.Resource.resx中⾃动⽣成的,代码如下:250internal static System.Drawing.Bitmap page_first251 {252get {253object obj = ResourceManager.GetObject ("page-first", resourceCulture);254return ( (System.Drawing.Bitmap) (obj) );255 }256 }257258internal static System.Drawing.Bitmap page_first_disabled259 {260get {261object obj = ResourceManager.GetObject ("page_first_disabled", resourceCulture);262return ( (System.Drawing.Bitmap) (obj) );263 }264 }265⼆是应⽤了委托事件:我们在这定义了⼀个分页事件266public event EventPagingHandler EventPaging;267在数据绑定⽅法中实现它:268///<summary>269///数据绑定270///</summary>271public void Bind()272 {273if (this.EventPaging != null)274 {275this.EventPaging (new EventArgs() );276 }277//… 以下省略278 }279这⾥需要⼤家对C#的委托和事件有⼀定的了解,不清楚的可以直接使⽤,或者先去查阅相关参考资料,这⾥我们就不谈委托机制了。

GridView+存储过程实现真分页

GridView+存储过程实现真分页

GridView+存储过程实现真分页GridView+存储过程实现'真分页',有需要的朋友可以参考下。

GridView,中的表格控件,和Repeater控件一样,在中都是很常用的两个表格控件,GridView自己也有分页功能,实现是将一张表的数据全部绑定到GridView,然后再进行分页,这就是通常我们所说的'假分页'。

在应对小数据量上完全没问题,但问题往往没有那么简单,在面对大数据量的问题上,GridView自己的分页还是力不从心,严重影响效率,用户体验也不好。

要解决这个问题,实现'真分页',就要从根上去分析,为什么'假分页'速度慢,因为它一次获取的是整张表的数据,但是最后显示的只是一页,所以,如果我们只查询需要显示的一页数据(上页下页,首页尾页,跳页都只查询需要的一页数据),在绑定到GridView中,查询分页的速度会快很多,这就是所谓的'真分页'了。

剩下的问题就是SQL语句去实现了。

经过一番查询研究,通过存储过程实现真分页效果挺好。

存储过程SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[PROC_GridViewPage]--@TableList Varchar(200), --查询的字段,用逗号隔开@TableName Varchar(30), --查询的表名--@SelectWhere Varchar(500),--查询的条件@SelectOrderId Varchar(20), --表主键字段名@SelectOrder Varchar(200), --排序,order by 列名@intPageNo int, --页号@intPageSize int, --每页显示数@RecordCount int OUTPUT --总记录数(OUTPUT表示是存储过程输出型参数,接收方法见DAL层)ASdeclare @TmpSelect NVarchar(600) --声明变量set nocount on --关闭计数--获取表中记录总数set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName+' ' --可以添加查询条件+@SelectWhereexecute sp_executesql@TmpSelect, --执行上面的sql语句N'@RecordCount int OUTPUT' , --执行输出数据的sql语句,output出总记录数@RecordCount OUTPUTif (@RecordCount = 0) --如果表中没有,则返回0return 0/*判断页数是否正确*/if (@intPageNo - 1) * @intPageSize > @RecordCount --页号大于总页数,返回错误return (-1)set nocount off--打开计数BEGINset @TmpSelect = 'select top '+str(@intPageSize)+' '+ '*' +'from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectOrder+') '+@SelectOrder ENDexecute sp_executesql @TmpSelectreturn(@@rowcount)GOsp_executesql?和EXEC一样在存储过程中执行sql语句的命令,平时我们见到和使用的通常是EXEC,sp_executesql的不同之出在于,它提供了一个借口,支持参数的输入和输出,灵活性更好,而且sp_executesql的执行性能更好。

如何实现GridView的手动分页

如何实现GridView的手动分页

如何实现GridView的手动分页我们可以这样做。

先要在Html界面中GridView中增加AllowPaging="True"接着做下面的//在page_load事件中将GridView绑定数据库protected void Page_Load(object sender, EventArgs e){string sqlstr=select * from TABLE;sqlconnection conn=new sqlconnection("数据库连接字串");DataSet mydataset = new DataSet();SqlDataAdapter myds = new SqlDataAdapter();myds.SelectCommand = new SqlCommand(sqlstr, conn);myds.Fill(mydataset);this.GridView1.DataSource = mydataset;mydataset.Dispose();myds.Dispose();conn.Close();conn.Dispose();GridView1.DataBind();}//GridView有一个PageIndexChanging事件protected void GridView1_PageIndexChanging(object sender, GridViewPag eEventArgs e){GridView1.PageIndex = e.NewPageIndex;GridView1.DataBind();}这样就可以实现啦!要使用手动分页前提是GridView没有使用数据源控件(sqldatasource.....)的时候。

请教GridView的手动分页如何实现?谢谢!请教GridView的手动分页(自定义分页)如何实现?比如已知有10000条数据,我要GridView的分页功能来显示数据,但是自动分页功能需要每次都取出全部的10000条数据,这样效率不高,所以就要求只用设置GridView的分页数如1000页(每页10知),当选择第n页时才从数据库中取出对应的数据,请问怎样实现?谢谢!结合存储过程写的通用搜索分页程序存储过程改自bigeagle的论坛分页程序。

MicrosoftVisualStudio2005中GridView手动分页,自定义分页(精)

MicrosoftVisualStudio2005中GridView手动分页,自定义分页(精)

1.创建存储过程,数据库为Microsoft SQL Server 2000,use Northwindgoselect * from Ordersgoif exists(select * from sysobjects where name='proc_ordersinfo' and type='P')drop procedure proc_ordersinfogo--创建查询表Orders的存储过程,@PageIndex 页面索引(页面索引=当前页数-1),@PageSize 每页显示数据的多少(多少行)--@PageCount 页面总数,@RecordCount 表中的记录总数create procedure proc_ordersinfo@PageIndex int,@PageSize int,@PageCount int outasdeclare @RecordCount int,@strsql nvarchar(1000)select @RecordCount=count(*) from ordersset @PageCount=ceiling(@RecordCount*1.0/@PageSize)--第1种情况,表只够分成一页if @PageIndex=0 or @PageCount<=1set @strsql=N'select top'+str(@PageSize)+'* from Orders order by OrderID desc' --第2种情况,要查询表的最后一页(可看作表Orders已被分成几个页了)else if @PageIndex=@PageCount-1set @strsql=N'select * from(selecttop'+str(@RecordCount-@PageIndex*@PageSize)+'* from Orders order by OrderID asc) TempTable order by OrderID desc'--第3种情况,查询非表的最后一页elseset @strsql=N'select top'+str(@PageSize)+'* from(selecttop'+str(@RecordCount-@PageIndex*@PageSize)+'* from Orders order by OrderID asc) TempTable order by OrderID desc'--执行SQL语句exec (@strsql)go2.创建显示数据的方法class CConnDB里的方法returnConn()返回数据库连接using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;//导入需要使用的命名空间using System.Data.SqlClient;/// <summary>/// CConnDB 的摘要说明/// </summary>public class CConnDB{public CConnDB(){//// TODO: 在此处添加构造函数逻辑//}public SqlConnection returnConn() {SqlConnection sconn = newSqlConnection("server=.;database=Northwind;uid=sa;pwd=sa");return sconn;}}class CDisplayOdersInfo里的方法DisplayOrdersInfo()返回一个DataSetusing System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;//导入需要使用的命名空间using System.Data.SqlClient;/// <summary>/// CDisplayOdersInfo 的摘要说明/// </summary>public class CDisplayOdersInfo{CConnDB ccdb = new CConnDB();//pageCount为页面总数private int pageCount;public CDisplayOdersInfo(){//// TODO: 在此处添加构造函数逻辑//}public DataSet DisplayOrdersInfo(int pageIndex,int pageSize) {SqlConnection sconn = ccdb.returnConn();SqlCommand scmd = new SqlCommand("proc_ordersinfo",sconn);scmd.Parameters.Add(new SqlParameter("@PageIndex",SqlDbType.Int));scmd.Parameters[0].Value = pageIndex;scmd.Parameters.Add(new SqlParameter("@PageSize",SqlDbType.Int));scmd.Parameters[1].Value = pageSize;scmd.Parameters.Add(new SqlParameter("@PageCount",SqlDbType.Int));scmd.Parameters[2].Direction = ParameterDirection.Output;mandType = CommandType.StoredProcedure;SqlDataAdapter sda = new SqlDataAdapter(scmd);DataSet ds = new DataSet();sda.Fill(ds);pageCount = (int)scmd.Parameters[2].Value;return ds;}public int returnPageCount() {return pageCount;}}3.页面设计和页面代码页面设计<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml" ><head runat="server"><title>无标题页</title></head><body><form id="form1" runat="server"><div>&nbsp;<asp:LinkButton ID="lbPrev" runat="server"OnClick="lbPrev_Click">上一页</asp:LinkButton><asp:Label ID="lblPageNum" runat="server"></asp:Label><asp:LinkButton ID="lbNext" runat="server" OnClick="lbNext_Click">下一页</asp:LinkButton><asp:GridView ID="gvMain" runat="server"></asp:GridView></div></form></body></html>页面代码using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{CDisplayOdersInfo cdoi = new CDisplayOdersInfo();//pageIndex 页面索引(页面索引=当前页数-1),pageSize 每页显示多少数据(多少行)//pageCount 页面的总页数private static int pageIndex = 0;private static int pageSize = 50;private static int pageCount = 0;protected void Page_Load(object sender, EventArgs e){if (!IsPostBack) {GridViewDataBind();}}private void GridViewDataBind() {DataSet ds= cdoi.DisplayOrdersInfo(pageIndex,pageSize);gvMain.DataSource = ds;gvMain.DataBind();pageCount = cdoi.returnPageCount();lblPageNum.Text ="当前页数:"+ Convert.ToString(pageIndex+1);}protected void lbPrev_Click(object sender, EventArgs e){pageIndex--;if (pageIndex < 0) {Response.Write("<script language=javascript>alert('已到首页!')</script>");pageIndex++;return;}GridViewDataBind();}protected void lbNext_Click(object sender, EventArgs e){pageIndex++;if (pageIndex >=pageCount){Response.Write("<script language=javascript>alert('已到尾页!')</script>");pageIndex--;return;}GridViewDataBind();}}。

让DataGridView控件里的记录分页显示

让DataGridView控件里的记录分页显示

让DataGridView控件里的记录分页显示一、数据准备二、分页逻辑实现记录分页显示的核心逻辑是将数据按照每页显示的记录数量进行切割,然后根据用户的操作加载不同的数据页。

下面是一个简单的分页逻辑示例:1.定义分页相关的变量:```csharpint pageSize = 10; // 每页显示的记录数量int totalPages = (data.Count + pageSize - 1) / pageSize; // 总页数``````csharpList<Record> currentPageData = data.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(;dataGridView.DataSource = currentPageData;``````csharpprivate void PreviousButton_Click(object sender, EventArgs e) if (currentPage > 1)currentPage--;LoadPageData(;}private void NextButton_Click(object sender, EventArgs e)if (currentPage < totalPages)currentPage++;LoadPageData(;}```三、界面设计四、性能优化在虚拟模式下,DataGridView控件只维护当前可见区域的数据,并在需要显示时动态加载数据。

可以通过实现DataGridView控件的CellValueNeeded事件来实现懒加载和虚拟模式。

具体实现方法超出了本文的范围,但是可以在MSDN文档或者各种技术论坛上找到详细的教程和示例。

总结:。

C#分页最好的实现方法

C#分页最好的实现方法
首先在数据库里建立以下存储过程: CREATE PROCEDURE dt_DXS_STAFF_ACTIVE @STAFFSTATUS INT,@STAFFNU M INT,@STARTNO INT,@@TOTALCOUNT INT OUTPUT,@@REALNUM INT OU TPUT AS
DECLARE @PRERECCOUNT VARCHAR(10) DECLARE @CURRECCOUNT VARCHAR(10) SELECT @@TOTALCOUNT=COUNT(*) FROM DXS_STAFF_ACTIVE IF @@TOTALCOUNT>(@STARTNO+1)*@STAFFNUM
LoadData(); } if (e.ClickedItem.Text == "下一页")
{ pageCurrent++; if (pageCurrent > pageCount) { MessageBox.Show("已经是最后一页,请点击“上一页”查看!"); return; } else { nCurrent=pageSize*(pageCurrent-1);
具体的建立存储过程我就不说了,简单说明一下以上语句的作用把。 CREATE PROCEDURE dt_DXS_STAFF_ACTIVE 其 实 就 是 生 成 一 个 名 为
dt_DXS_STAFF_ACTIVE 的存储过程,具体命名按实际需要。
TOTALCOUNT:数据行总数。 REALNUM:当前记录数。 以下是将数据导入页面的函数:
ELSE BEGIN SET @PRERECCOUNT= CAST( @STARTNO * @STAFFNUM AS VARCHA

C# 实现Winform控件dataGridView的打印与分页

C# 实现Winform控件dataGridView的打印与分页

本文档是参考网上的资料,稍加修改,经过实际编译,可实现Winform上dataGridView控件的打印,并实现分页,下面为程序代码,仅供参考。

本程序不需要在界面上添加任何打印相关控件。

public partial class Example : Form{//打印文檔PrintDocument pdDocument = new PrintDocument();//打印格式設置頁面PageSetupDialog dlgPageSetup = new PageSetupDialog();//打印頁面PrintDialog dlgPrint = new PrintDialog();//實例化打印預覽PrintPreviewDialog dlgPrintPreview = new PrintPreviewDialog();public Example(){InitializeComponent();pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);//頁面設置的打印文檔設置為需要打印的文檔dlgPageSetup.Document = pdDocument;//打印界面的打印文檔設置為被打印文檔dlgPrint.Document = pdDocument;//打印預覽的打印文檔設置為被打印文檔dlgPrintPreview.Document = pdDocument;}///<summary>/// //顯示打印預覽界面,此处需要添加一个打印预览的按钮///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnPrintView_Click(object sender, EventArgs e){dlgPrintPreview.ShowDialog();}///打印设置,此处需要添加一个打印设置的按钮///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnPrintSetup_Click(object sender, EventArgs e){dlgPageSetup.ShowDialog();dlgPrint.ShowDialog();}////// printDocument的PrintPage事件,实现打印功能/////////private void OnPrintPage(object sender, PrintPageEventArgs e){int iX = 60;int iY = 40;PrintDataGridView11.Print(dataGridView1, true, e, ref iX, ref iY);}///<summary>///打印,此处需添加一个打印按钮///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnPrint_Click(object sender, EventArgs e){pdDocument.Print();}}///<summary>///实现DataGridView的打印类///</summary>public class PrintDataGridView11{private static List<DataGridViewCellPrint> CellPrintList = newList<DataGridViewCellPrint>();///<summary>///打印的行数private static int printRowCount = 0;///<summary>///是否要打印///</summary>private static bool IsPrint = true;///<summary>///设置的起始位置是否大于默认打印的边框///</summary>private static bool IsRole = true;///<summary>/// X坐标///</summary>private static int PoXTmp = 0;///<summary>/// Y坐标///</summary>private static int PoYTmp = 0;///<summary>///列间距///</summary>private static int WidthTmp = 0;///<summary>///行间距///</summary>private static int HeightTmp = 0;///<summary>///列数///</summary>private static int RowIndex = 0;//////打印DataGridView控件////// DataGridView控件///是否包括列标题///为System.Drawing.Printing.PrintDocument.PrintPage 事件提供数据。

关于GridView的分页-万能分页代码

关于GridView的分页-万能分页代码

关于GridView的分页-万能分页代码大家往往在分页时感觉不好控制,在这里只需要在GridView里面的PagerTemplate模板里进行设置就可以了。

具体就是在GridView里面添加如下:C# code<PagerTemplate><div style="text-align:center; color:Blue"><asp:LinkButton ID="cmdFirstPage" runat="server" CommandName="Page" CommandArgument="First"Enabled="<%# ((GridView)Container.Parent.Parent).PageIndex!=0 %>">首页</asp:LinkButton><asp:LinkButton ID="cmdPreview" runat="server" CommandArgument="Prev" CommandName="Page"Enabled="<%# ((GridView)Container.Parent.Parent).PageIndex!=0 %>">前页</asp:LinkButton>第<asp:Label ID="lblcurPage" ForeColor="Blue" runat="server" Text='<%# ((GridView)Container.Parent.Parent).PageIndex+1 %>'></asp:Label>页/共<asp:Label ID="lblPageCount" ForeColor="blue" runat="server" Text='<%#((GridView)Container.Parent.Parent).PageCount %>'></asp:Label>页<asp:LinkButton ID="cmdNext" runat="server" CommandName="Page" CommandArgument="Next"Enabled="<%#((GridView)Container.Parent.Parent).PageIndex!=((GridView)Container.Parent.Par ent).P ageCount-1 %>">后页</asp:LinkButton><asp:LinkButton ID="cmdLastPage" runat="server" CommandArgument="Last" CommandName="Page"Enabled="<%#((GridView)Container.Parent.Parent).PageIndex!=((GridView)Container.Parent.Parent).P ageCount-1 %>">尾页</asp:LinkButton>&nbsp;<asp:TextBox ID="txtGoPage" OnTextChanged="txtGoPage_TextChanged" runat="server" Text='<%# ((GridView)Container.Parent.Parent).PageIndex+1 %>' Width="32px" CssClass="inputmini"></asp:TextBox>页<asp:Button ID="Button3" runat="server"OnClick="Turn_Click" Text="转到" /></div></PagerTemplate>这样只需在后台填写两个事件:GridView1_PageIndexChanging和Turn_ClickC# codeprotected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {GridView1.PageIndex = e.NewPageIndex;bind();//对GridView进行再次绑定,该函数由自己编写}protected void Turn_Click(object sender, EventArgs e){GridView1.PageIndex =int.Parse(((TextBox)GridView1.BottomPagerRow.FindControl("txtGoPage")).Text)-1;bind();//对GridView进行再次绑定,该函数由自己编写}。

GridView控件自定义分页详解

GridView控件自定义分页详解

GridView控件自定义分页详解在这里我们将用一个隐藏字段来保存这个PageIndex,即当前页码.当点击上一页时,将它的值减一,知道为0,要注意的一点这里的第一页页码是0而不是1.下面看看代码,然后我们再分析分析!1<asp:GridView ID="NewsGrid" runat="server" AutoGenerateColumns="False" AllowPaging="false" Width="100%">2 <Columns>3 <asp:BoundField DataField="NewsId" HeaderText="新闻ID"/>4 <asp:HyperLinkField DataNavigateUrlFields="NewsId" DataNavigateUrlFormatString="~/Details.aspx?ID={0}"5 DataTextField="Title" HeaderText="新闻标题" ItemStyle-Width="70%"/>6 <asp:BoundField DataField="PostTime" HeaderText="发布时间"/>7 <asp:CommandField HeaderText="新闻管理" ShowCancelButton="False" ShowDeleteButton="True"8 ShowEditButton="True"/>9 </Columns>10 </asp:GridView>实用文档11 <div style=" height:16px; padding-top:5px; margin-right:30px; float:right">12 <asp:HiddenField ID="CurrentPage" runat="server" Value="0"/>13 <asp:LinkButton ID="First" runat="server" CommandArgument="first" OnClick="PagerButton_Click">首页</asp:LinkButton>14 <asp:LinkButton ID="Prev" runat="server" CommandArgument="prev" OnClick="PagerButton_Click">上一页</asp:LinkButton>15 <asp:LinkButton ID="Next" runat="server" CommandArgument="next" OnClick="PagerButton_Click">下一页</asp:LinkButton>16 <asp:LinkButton ID="Last" runat="server" CommandArgument="last" OnClick="PagerButton_Click">尾页</asp:LinkButton>17 </div> CS文件中的代码:1 protected void PagerButton_Click(object sender, EventArgs e)2 {3 int pageIndx = Convert.ToInt32(CurrentPage.Value);4 int totals = NewsManager.GetNews(0, pageSize).TotalRecords;5 int pages = (totals % pageSize) == 0 ? (totals / pageSize) : (totals / 实用文档pageSize + 1);6 string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();7 switch (arg)8 {9 case "prev":10 if (pageIndx > 0)11 {12 pageIndx -= 1;13 }14 break;15 case "next":16 if (pageIndx < pages - 1)17 {18 pageIndx += 1;19 }20 break;21 case "last":实用文档22 pageIndx = pages - 1;23 break;24 default:25 pageIndx = 0;26 break;27 }28 CurrentPage.Value = pageIndx.ToString();29 NewsGrid.DataSource = NewsManager.GetNews(pageIndx , pageSize).Entities;30 NewsGrid.DataBind();31 }如何在GridView中增加效果protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){//将满足特定条件的行标为高亮if (e.Row.RowType == DataControlRowType.DataRow)//判定当前的行是否属于datarow类型的行实用文档{int money = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "MONEY"));//取当前行的列值if (money == 77)e.Row.BackColor = Color.Red;//string customer = (string)DataBinder.Eval(e.Row.DataItem, "CUSTOMER");string customer = DataBinder.Eval(e.Row.DataItem, "CUSTOMER").ToString();if (customer == "sdf")e.Row.BackColor = Color.Red;}//加入鼠标滑过的高亮效果if (e.Row.RowType == DataControlRowType.DataRow)//判定当前的行是否属于datarow类型的行{//当鼠标放上去的时候先保存当前行的背景颜色并给附一颜色e.Row.Attributes.Add("onmouseover", 实用文档"currentcolor=this.style.backgroundColor;this.style.backgroundColor='yellow',t his.style.fontWeight='';");//当鼠标离开的时候将背景颜色还原的以前的颜色e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");}//单击行改变行背景颜色if (e.Row.RowType == DataControlRowType.DataRow){e.Row.Attributes.Add("onclick","this.style.backgroundColor='#99cc00'; this.style.color='buttontext';this.style.cursor='default';");}如何在GridView中一次性批量更新多行数据2.0下含有DropDownList的GridView编辑、删除的完整例子!<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" PageSize="10"实用文档Width="542px" AllowPaging="True" AllowSorting="True"DataKeyNames="DB31_1,DB31_2" OnRowCancelingEdit="GridView1_RowCancelingEdit"OnRowDeleting="GridView1_RowDeleting"OnRowEditing="GridView1_RowEditing"OnRowUpdating="GridView1_RowUpdating"OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"OnSorting="GridView1_Sorting" ><Columns><asp:TemplateField HeaderText="序号"><ItemTemplate><%# this.GridView1.PageIndex * this.GridView1.PageSize + this.GridView1.Rows.Count + 1%></ItemTemplate></asp:TemplateField>实用文档<asp:TemplateField HeaderText="学历代码" SortExpression="DB1_1"><EditItemTemplate><%--<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("DB1_1") %>'></asp:TextBox>--%><asp:DropDownList ID ="ddlXL"runat="server" DataValueField='<%#Bind("DB1_1") %>'></asp:DropDownList></EditItemTemplate><ItemTemplate><asp:Label ID="Label1" runat="server" Text='<%# Bind("xueliText") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="学历名称" SortExpression="DB1_2"><EditItemTemplate>实用文档<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("DB1_2") %>'></asp:TextBox></EditItemTemplate><ItemTemplate><asp:Label ID="Label2" runat="server" Text='<%# Bind("DB1_2") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="操作" ShowHeader="False"><EditItemTemplate><asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"Text="更新"></asp:LinkButton><asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"实用文档Text="取消"></asp:LinkButton></EditItemTemplate><ItemTemplate><asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"Text="编辑" OnClientClick="return confirm('确认要编辑吗?');"></asp:LinkButton><asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Delete"Text="删除" OnClientClick="return confirm('确认要删除吗?');"></asp:LinkButton><asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Select"Text="选择"></asp:LinkButton></ItemTemplate>实用文档</asp:TemplateField></Columns><AlternatingRowStyle BackColor="Aquamarine" /></asp:GridView>/// <summary>/// 绑定数据到GridView/// </summary>private void GridViewBind(){检索数据库string strSql = "SELECT * FROM DB1";得到数据集this.GridView1.DataSource=conn.GetDs(strSql).Tables[0].DefaultView;this.GridView1.DataBind();实用文档}/// <summary>/// 编辑当前行/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e){GridView1.EditIndex = e.NewEditIndex;//当前编辑行背景色高亮this.GridView1.EditRowStyle.BackColor = Color.FromName("#F7CE90");GridViewBind();}/// <summary>实用文档/// 取消编辑状态/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e){GridView1.EditIndex = -1;GridViewBind();}/// <summary>/// 删除记录过程/// </summary>/// <param name="sender"></param>/// <param name="e"></param>实用文档protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){//得到单位编号string rowToDelete =GridView1.DataKeys[e.RowIndex].Values[0].ToString();//转换为整数//int ID=Convert.ToInt32(rowToDelete);//从数据库中删除string str = "DELETE FROM DB1 where DB1_1=" + "'" + rowToDelete + "'" + "";try{conn.RunSql(str);//重新绑定数据实用文档GridViewBind();}catch (Exception ex){Response.Write("数据库错误,错误原因:" + ex.Message);Response.End();}}/// <summary>/// 更新记录过程/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)实用文档{string ID = GridView1.DataKeys[e.RowIndex].Values[0].ToString();string DB1_1 =((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;//string DB1_2 =((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;string DB1_2 =(((DropDownList))GridView1.Rows[e.RowIndex].FindControl("ddlXL")).SelectedI tem.Text;//判断表单项是否有空并给出提示信息if (DB1_1 == "" || DB1_2 == ""){conn.Alert("请输入完整信息!", Page);return;}实用文档try{conn.BuilderEdit("select * from DB1 where DB1_1 ='" + ID + "'");conn.dr["DB1_1"] = DB1_1;conn.dr["DB1_2"] = DB1_2;conn.BuilderEditClose();}catch (OracleException err){if (err.Code.ToString() == "1")conn.Alert("错误:已存在具有相同主键的记录", Page);elseconn.Alert("错误:未能添加记录", Page);}实用文档Response.Write("<script language='javascript'>alert('数据已被保存!');</script>");//返回浏览状态GridView1.EditIndex = -1;GridViewBind();}/// <summary>/// 分页事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e){GridView1.PageIndex = e.NewPageIndex;GridViewBind();实用文档}/// <summary>/// 加入鼠标效果及为DropDownList绑定值/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){//为DropDownList绑定值if (((DropDownList)e.Row.FindControl("ddlXL")) != null){DropDownList ddlXL = (DropDownList)e.Row.FindControl("ddlXL");ddlXL.Items.Clear();ddlXL.Items.Add(new ListItem("博士", "1"));实用文档ddlXL.Items.Add(new ListItem("硕士", "2"));ddlXL.Items.Add(new ListItem("学士", "3"));}//加入鼠标滑过的高亮效果if (e.Row.RowType == DataControlRowType.DataRow)//判定当前的行是否属于datarow类型的行{//当鼠标放上去的时候先保存当前行的背景颜色并给附一颜色e.Row.Attributes.Add("onmouseover","currentcolor=this.style.backgroundColor;this.style.backgroundColor='yellow',t his.style.fontWeight='';");//当鼠标离开的时候将背景颜色还原的以前的颜色e.Row.Attributes.Add("onmouseout","this.style.backgroundColor=currentcolor,this.style.fontWeight='';");}//单击行改变行背景颜色实用文档if (e.Row.RowType == DataControlRowType.DataRow){e.Row.Attributes.Add("onclick", "this.style.backgroundColor='#99cc00'; this.style.color='buttontext';this.style.cursor='default';");}}2.0下含有CheckBox的GridView删除选定记录实例<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" PageSize="5"2 Width="726px" AllowPaging="True" AllowSorting="True"3 DataKeyNames="DB1_1,DB1_2" OnRowDeleting="GridVie w1_RowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound"OnSorting="GridView1_Sorting" Height="279px" >4 <Columns>实用文档5 <asp:TemplateField HeaderText="序号" >6 <ItemTemplate>7 <%# this.GridView1.PageIndex *this.GridView1.PageSize + this.GridView1.Rows.Count + 1%>8 </ItemTemplate>9 </asp:TemplateField>10 <asp:TemplateField HeaderText="选择" >11 <ItemTemplate>12 <asp:CheckBox ID="chkSelect" runat="server" ></asp:CheckBox>13 </ItemTemplate>14 </asp:TemplateField>15 <asp:TemplateField HeaderText="操作" ShowHeader="False">16 <ItemTemplate>实用文档17 <asp:LinkButton ID="lbtnDelete" runat="server" CausesValidation="False" CommandName="Delete"18 Text="删除" OnClientClick="return confirm('确认要删除吗?');"></asp:LinkButton>19 </ItemTemplate>20 </asp:TemplateField>21 </Columns>22 <AlternatingRowStyle BackColor="Aquamarine" />23 </asp:GridView>1 <asp:CheckBox ID="chkSelectAll" runat="server" Text="全部选中" OnCheckedChanged="chkSelectAll_CheckedChanged"AutoPostBack="True" ></asp:CheckBox>2 <asp:Button ID="btnDelete" runat="server" Text="删除" OnClick="btnDelete_Click" />1 protected void btnDelete_Click(object sender, EventArgs e)2 {实用文档3 string strDelete = "";4 for (int i = 0; i < this.GridView1.Rows.Count; i++)5 {6 string Label;7 bool isChecked =((CheckBox)GridView1.Rows[i].FindControl("chkSelect")).Checked;8 Label = ((Label)GridView1.Rows[i].FindControl("labXH")).Text;9 if (isChecked)10 {11 strDelete = "DB1_1" + "=" + Label;12 }13 }14 conn.RunSql("Delete from DB1 where " + strDelete15 this.chkSelectAll.Checked = false;16 GridViewBind();实用文档17 }1819 protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)20 {21 //遍历GridView行获取CheckBox属性22 for (int i = 0; i < this.GridView1.Rows.Count; i++)23 {24 ((CheckBox)GridView1.Rows[i].FindControl("chkSelect")).Checked = this.chkSelectAll.Checked;25 }26 }实用文档。

C#_实现Winform控件dataGridView的打印与分页

C#_实现Winform控件dataGridView的打印与分页

本文档是参考网上的资料,稍加修改,经过实际编译,可实现Winform上dataGridView控件的打印,并实现分页,下面为程序代码,仅供参考。

本程序不需要在界面上添加任何打印相关控件。

public partial class Example : Form{//打印文檔PrintDocument pdDocument = new PrintDocument();//打印格式設置頁面PageSetupDialog dlgPageSetup = new PageSetupDialog();//打印頁面PrintDialog dlgPrint = new PrintDialog();//實例化打印預覽PrintPreviewDialog dlgPrintPreview = new PrintPreviewDialog();public Example(){InitializeComponent();pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);//頁面設置的打印文檔設置為需要打印的文檔dlgPageSetup.Document = pdDocument;//打印界面的打印文檔設置為被打印文檔dlgPrint.Document = pdDocument;//打印預覽的打印文檔設置為被打印文檔dlgPrintPreview.Document = pdDocument;}///<summary>/// //顯示打印預覽界面,此处需要添加一个打印预览的按钮///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnPrintView_Click(object sender, EventArgs e){dlgPrintPreview.ShowDialog();}///打印设置,此处需要添加一个打印设置的按钮///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnPrintSetup_Click(object sender, EventArgs e){dlgPageSetup.ShowDialog();dlgPrint.ShowDialog();}////// printDocument的PrintPage事件,实现打印功能/////////private void OnPrintPage(object sender, PrintPageEventArgs e){int iX = 60;int iY = 40;PrintDataGridView11.Print(dataGridView1, true, e, ref iX, ref iY);}///<summary>///打印,此处需添加一个打印按钮///</summary>///<param name="sender"></param>///<param name="e"></param>private void btnPrint_Click(object sender, EventArgs e){pdDocument.Print();}}///<summary>///实现DataGridView的打印类///</summary>public class PrintDataGridView11{private static List<DataGridViewCellPrint> CellPrintList = newList<DataGridViewCellPrint>();///<summary>///打印的行数private static int printRowCount = 0;///<summary>///是否要打印///</summary>private static bool IsPrint = true;///<summary>///设置的起始位置是否大于默认打印的边框///</summary>private static bool IsRole = true;///<summary>/// X坐标///</summary>private static int PoXTmp = 0;///<summary>/// Y坐标///</summary>private static int PoYTmp = 0;///<summary>///列间距///</summary>private static int WidthTmp = 0;///<summary>///行间距///</summary>private static int HeightTmp = 0;///<summary>///列数///</summary>private static int RowIndex = 0;//////打印DataGridView控件////// DataGridView控件///是否包括列标题///为System.Drawing.Printing.PrintDocument.PrintPage 事件提供数据。

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

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

EXEC( 'SELECT TOP ' + @CurRecCount + ' * FROM EmployeeInfo WHERE EmployeeID NOT IN ' + '(SELECT TOP ' + @PreRecCount + ' EmployeeID FROM EmployeeInfo ORDER BY EmployeeID ASC) '+ 'ORDER BY EmployeeID ASC')ENDGO然后就是调用存储过程来进行显示,比较完整的源代码如下://------------------------ 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 ponentModel;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 bel 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 ponentModel.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 bel();this .btnPrevious = new System.Windows.Forms.Button();this .btnNext = new System.Windows.Forms.Button();((ponentModel.ISupportInitialize)(this .dtgUserInfo)).BeginIn it();this .SuspendLayout();//// dtgUserInfo//this .dtgUserInfo.DataMember = "";this .dtgUserInfo.HeaderForeColor =System.Drawing.SystemColors.ControlText;this .dtgUserInfo.Location = new System.Drawing.Point(16, 16);this = "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";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";this .btnPrevious.TabIndex = 2;this .btnPrevious.Text = "Previous";this .btnPrevious.Click += newSystem.EventHandler(this .btnPrevious_Click);//// btnNext//this .btnNext.Location = new System.Drawing.Point(488, 440);this = "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);((ponentModel.ISupportInitialize)(this .dtgUserInfo)).EndInit ();this .ResumeLayout(false );}#endregionprivate void frmMultiPages_Load(object sender, System.EventArgs e){//Set connection stringsqlConn.ConnectionString = yourconnectionstring;//Connect to DBif ( ConnectDB() ){//Bind data to datagridBindData();}}///<summary>///Connect to DB///</summary>///<returns>If connected, return True; else return False</returns>private bool ConnectDB(){//Check current connection's statetry{if ( sqlConn.State == ConnectionState.Closed || sqlConn.State == ConnectionState.Broken ) {//Connection is not availablesqlConn.Close();}else//Connection is availablereturn true ;}catch {};//Re-connecttry{sqlConn.Open();}catch (SqlException e){//Sql's exceptionMessageBox.Show( e.Message );}catch (Exception e){//Other exceptionMessageBox.Show( e.Message );}if ( sqlConn.State == ConnectionState.Closed|| sqlConn.State == ConnectionState.Broken )//Connection is not availablereturn false ;else//Connection is availablereturn 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 = newDataGridTextBoxColumn( 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;mandText = "GetEmployees";mandType = 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 datasetsqlRecordSet = 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 ;elsebtnNext.Enabled = true ;if ( nCurPageNum == 0 )btnPrevious.Enabled = false ;elsebtnPrevious.Enabled = true ;}private void BindData(){GetEmployeeData();//Bind datagrid with datasetdtgUserInfo.SetDataBinding( sqlRecordSet, "EmployeeInfo");//Add datagrid styleAddDGStyle();}private void ReBindData(){GetEmployeeData();//Bind datagrid with datasetdtgUserInfo.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 datagridview控件用法

winform datagridview控件用法

winform datagridview控件用法Winform DataGridView 控件用法详解一、简介Winform DataGridView 控件是 .NET Framework 中提供的一个强大的数据显示和编辑控件。

它可以显示和编辑多种类型的数据(如文本、数字、日期、图像等),并且提供了丰富的功能和灵活的样式设置,可以方便地实现数据的展示、排序、筛选、编辑、分页等操作。

二、绑定数据源1. 绑定数据集可以通过设置DataGridView 的DataSource 属性来绑定一个数据集(DataSet)或数据表(DataTable)。

在Visual Studio 的设计器中,通过选择数据源和数据成员来实现绑定,也可以通过代码实现。

例如:dataGridView1.DataSource = dataSet.Tables["TableName"];2. 绑定数据集合除了绑定数据集,还可以绑定数据集合(如List<T>、BindingList<T> 等)。

在数据集合发生变化时,DataGridView 会自动更新显示的数据。

例如:List<User> userList = new List<User>();dataGridView1.DataSource = userList;3. 动态绑定数据绑定数据源后,可以通过设置DataGridView 的AutoGenerateColumns 属性为true,自动根据数据源的结构创建列。

也可以通过手动添加列来控制显示的列数和顺序。

例如:dataGridView1.AutoGenerateColumns = true;三、设置列样式1. 自动调整列宽可以通过设置DataGridView 的AutoSizeColumnsMode 属性来调整列宽。

通常选择AllCells 或Fill,前者会根据列中的内容调整列宽,后者会填充整个控件。

让DataGridView控件里的记录分页显示

让DataGridView控件里的记录分页显示

让DataGridView控件里的记录分页显示让DataGridView控件里的记录分页显示 ( 2005)Public Class ClsDataGridViewPage'每页记录数Private _RowsPerPage As Integer'总页数Private _TotalPage As Integer'当前页数Private _curPage As Integer = 0'要分页的DataGridViewPrivate _DataGridView As Windows.Forms.DataGridView '与需要分页显示的的DataViewPrivate _dv As DataView'获取与设置每页记录数Public Property RowsPerPage() As IntegerGetReturn _RowsPerPageEnd GetSet(ByVal value As Integer)_RowsPerPage = valueEnd SetEnd Property'获取总页数Public ReadOnly Property TotalPage() As IntegerGetReturn _TotalPageEnd GetEnd Property'获取与设置当前页数Public Property curPage() As IntegerGetReturn _curPageEnd GetSet(ByVal value As Integer)_curPage = valueEnd SetEnd Property'设置需要分页的GetDataGridViewPublic WriteOnly Property SetDataGridView()Set(ByVal value As Object)_DataGridView = valueEnd SetEnd Property'设置需要分页显示的的DataViewPublic WriteOnly Property SetDataView()Set(ByVal value As Object)_dv = valueEnd SetEnd PropertyPublic Sub New()End Sub'重载NEW函数,在构造时就可以对成员赋值Public Sub New(ByVal datagridview As Windows.Forms.DataGridView, ByVal dv As DataView, _ByVal RowsPerPage As Integer)_DataGridView = datagridview_dv = dv_RowsPerPage = RowsPerPageEnd Sub'开始分页啦Public Sub Paging()'首先判断DataView中的记录数是否足够形成多页,'如果不能,那么就只有一页,且DataGridView需要显示的记录等同于“最后一页”的记录If _dv.Count <= _RowsPerPage Then_TotalPage = 1GoLastPage()Exit SubEnd If'可以分为多页的话就要计算总的页数咯,然后DataGridView显示第一页If _dv.Count Mod _RowsPerPage = 0 Then_TotalPage = Int(_dv.Count / _RowsPerPage)Else_TotalPage = Int(_dv.Count / _RowsPerPage) + 1End IfGoFirstPage()End Sub'到第一页Public Sub GoFirstPage()'如果只有一页,那么显示的记录等同于“最后一页”的记录 If _TotalPage = 1 ThenGoLastPage()Exit SubEnd If'如果有多页,就到第“1”页_curPage = 0GoNoPage(_curPage)End SubPublic Sub GoNextPage()'这段代码主要是为了防止当前页号溢出_curPage += 1If _curPage > _TotalPage - 1 Then_curPage = _TotalPage - 1Exit SubEnd If'如果到了最后一页,那就显示最后一页的记录If _curPage = _TotalPage - 1 ThenGoLastPage()Exit SubEnd If'如果没到最后一页,就到指定的“下一页”GoNoPage(_curPage)End SubPublic Sub GoPrevPage()'防止不合法的当前页号_curPage -= 1If _curPage < 0 Then_curPage = 0Exit SubEnd If'到指定的“上一页”GoNoPage(_curPage)End Sub'到最后一页Public Sub GoLastPage()_curPage = _TotalPage - 1Dim i As IntegerDim dt As New DataTable'dt只是个临时的DataTable,用来获取所需页数的记录dt = _dv.ToTable.CloneFor i = (_TotalPage - 1) * _RowsPerPage To _dv.Count - 1'i值上下限很关键,调试的时候常常这里报错找不到行'就是因为i值溢出Dim dr As DataRow = dt.NewRowdr.ItemArray = _dv.ToTable.Rows(i).ItemArraydt.Rows.Add(dr)Next_DataGridView.DataSource = dtEnd Sub'到指定的页Public Sub GoNoPage(ByVal PageNo As Integer)_curPage = PageNo'防止不合法的页号If _curPage < 0 ThenMsgBox("页号不能小于1")Exit SubEnd If'防止页号溢出If _curPage >= _TotalPage ThenMsgBox("页号超出上限")Exit SubEnd If'如果页号是最后一页,就显示最后一页If _curPage = _TotalPage - 1 ThenGoLastPage()Exit SubEnd If'不是最后一页,那显示指定页号的页Dim dt As New DataTabledt = _dv.ToTable.CloneDim i As IntegerFor i = PageNo * _RowsPerPage To (PageNo + 1) * _RowsPerPage - 1Dim dr As DataRow = dt.NewRowdr.ItemArray = _dv.ToTable.Rows(i).ItemArraydt.Rows.Add(dr)Next_DataGridView.DataSource = dtEnd SubEnd Class现在举例介绍一下怎么使用这个类(以下简称分页辅助类)来帮助DataGridView控件分页显示记录:首先,在DataGridView所在的窗体类代码中加入该分页辅助类的成员:Private dgvPage As ClsDataGridViewPage然后在窗体的构造函数代码中实例化这个成员:Public Sub New()' 此调用是 Windows 窗体设计器所必需的。

DataGridView使用自定义控件实现简单分页功能(推荐)

DataGridView使用自定义控件实现简单分页功能(推荐)

DataGridView使⽤⾃定义控件实现简单分页功能(推荐)本例⼦使⽤⾃定义控件⽅法实现,数据库使⽤的是SQL Server,实现过程如下:1、新建⼀个⾃定义控件,命名为:PageControl。

2、PageControl代码如下:public partial class PageControl : UserControl{//委托及事件public delegate void BindPage(int pageSize, int pageIndex, out int totalCount);public event BindPage BindPageEvent;//属性public int PageSize { get; set; } = 1; //每页显⽰记录数public int PageIndex { get; set; } //页序号public int TotalCount { get; set; } //总记录数public int PageCount { get; set; } //总页数public PageControl(){InitializeComponent();//取消下划线linkFirst.LinkBehavior = LinkBehavior.NeverUnderline;linkPrev.LinkBehavior = LinkBehavior.NeverUnderline;linkNext.LinkBehavior = LinkBehavior.NeverUnderline;linkLast.LinkBehavior = LinkBehavior.NeverUnderline;linkGo.LinkBehavior = LinkBehavior.NeverUnderline;}/// <summary>/// 设置页/// </summary>public void SetPage(){//总记录数int totalCount = 0;BindPageEvent(PageSize, PageIndex + 1, out totalCount);TotalCount = totalCount;//总页数if (TotalCount % PageSize == 0)PageCount = TotalCount / PageSize;elsePageCount = TotalCount / PageSize + 1;//当前页及总页数txtCurrentPage.Text = (PageIndex + 1).ToString();lblTotalPage.Text = "共 " + PageCount.ToString() + " 页";}/// <summary>/// ⾸页/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void linkFirst_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){if (e.Button == MouseButtons.Left){PageIndex = 0;SetPage();}}/// <summary>/// 上⼀页/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void linkPrve_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){if (e.Button == MouseButtons.Left){PageIndex--;if (PageIndex < 0){PageIndex = 0;}SetPage();}}/// <summary>/// 下⼀页/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void linkNext_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){if (e.Button == MouseButtons.Left){PageIndex++;if (PageIndex > PageCount - 1){PageIndex = PageCount - 1;}SetPage();}}/// <summary>/// 末页/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void linkLast_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){if (e.Button == MouseButtons.Left){PageIndex = PageCount - 1;SetPage();}}/// <summary>/// 只能按0-9、Delete、Enter、Backspace键/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void txtSetPage_KeyPress(object sender, KeyPressEventArgs e){if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8 || e.KeyChar == 13 || e.KeyChar == 127){e.Handled = false;if (e.KeyChar == 13){Go();}}else{e.Handled = true;}}/// <summary>/// 指定页/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void linkGo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){if (e.Button == MouseButtons.Left){Go();}}private void Go(){if (string.IsNullOrEmpty(txtCurrentPage.Text)){MessageBox.Show("指定页不能为空。

实现DataGridview中的分页显示

实现DataGridview中的分页显示

数据库存储过程分页与SQL调用CREATE PROCEDURE [dbo].[Pagination]@Columns VARCHAR(500),-- The columns to be displayed, divide by comma @Tablename VARCHAR(100),-- The name of the table to be searched@OrderColumnName VARCHAR(100),-- The name of the column to be used in order@Order VARCHAR(50),-- The order method, ASC or DESC@Where VARCHAR(100),-- The where condition, if there is not conditon use 1=1@PageIndex INT,-- Current page index@PageSize INT,-- The size of the page@PageCount INT OUTPUT-- The total page count,define as output parameter ASBEGINDECLARE@SqlRecordCount NVARCHAR(100)-- The SQL Statement to get the total count of the recordsDECLARE @SqlSelect NVARCHAR(1000)-- The SQL SELECT statmentSET@SqlRecordCount =N'SELECT @RecordCount = COUNT(*) FROM '+@Tablename +' WHERE '+@WhereDECLARE @RecordCount INTEXEC sp_executesql @SqlRecordCount, N'@RecordCount INTOUTPUT',@RecordCount OUTPUT-- Transfer the parameter dynamicIF(@RecordCount % @PageSize = 0)SET @PageCount = @RecordCount / @PageSizeELSESET @PageCount = @RecordCount / @PageSize + 1SET@SqlSelect =N'SELECT '+@Columns +' FROM(SELECT ROW_NUMBER() OVER (ORDER BY '+ @OrderColumnName+' '+ @Order +') AS tempid, * FROM '+ @Tablename +' WHERE '+ @Where +') AS tempTableName WHERE tempid BETWEEN '+STR((@PageIndex - 1)*@PageSize + 1)+' AND '+STR(@PageIndex * @PageSize)EXEC(@SqlSelect)END程序有3个控件BindingNavigator:就是DataGridView控件上面的那个,在工程里名字:bindngrDemo DataGridView: dgvDemoBindingSource: 这个其实可以不要bindseDemousing System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Collections;using System.Data.SqlClient;using System.Configuration;namespace FeiTianSeo{public partial class Test1 : Form{static int pageSize = 20;static int pageCount = 0;public Test1(){InitializeComponent();}public static string connectionString = ConfigurationManager.ConnectionStrings["conn"].ToString();private void Test1_Load(object sender, EventArgs e) {LoadData(1, dgvDemo);// Set the status of the BindingNavigator controlif (pageCount == 0 || pageCount == 1){bindngrDemo.MoveFirstItem.Enabled = false;bindngrDemo.MoveLastItem.Enabled = false;bindngrDemo.MoveNextItem.Enabled = false;bindngrDemo.MovePreviousItem.Enabled = false;}else{bindngrDemo.MoveFirstItem.Enabled = false;bindngrDemo.MoveLastItem.Enabled = true;bindngrDemo.MoveNextItem.Enabled = true;bindngrDemo.MovePreviousItem.Enabled = false;bindngrDemo.PositionItem.Text = "1";bindngrDemo.CountItem.Text = "共{" + pageCount.ToString() + "}页";}}private static SqlCommand GenerateSelectCommand(string Columns, string tableName, string orderColumnName, string order, string whereCondition,int pageIndex, int pageSize, SqlConnection conn){SqlCommand sqlcmd = new SqlCommand("Pagination", conn);调用存储过程计算求分页数 mandType = CommandType.StoredProcedure;sqlcmd.Parameters.AddWithValue("@Columns", Columns);sqlcmd.Parameters.AddWithValue("@Tablename", tableName);sqlcmd.Parameters.AddWithValue("@OrderColumnName", orderColumnName);sqlcmd.Parameters.AddWithValue("@Order", order);sqlcmd.Parameters.AddWithValue("@Where", whereCondition);sqlcmd.Parameters.AddWithValue("@PageIndex", pageIndex);sqlcmd.Parameters.AddWithValue("@PageSize", pageSize);SqlParameter pageCount = new SqlParameter("@PageCount", SqlDbType.Int);pageCount.Direction = ParameterDirection.Output;sqlcmd.Parameters.Add(pageCount);sqlcmd.UpdatedRowSource = UpdateRowSource.None;return sqlcmd;}private static void LoadData(int pageIndex, DataGridView dgvDemo){//string strConn = "server = (local); Database = pubs; Integrated Security = SSPI";try{using (SqlConnection conn = new SqlConnection(connectionString)){conn.Open();SqlDataAdapter sqlDa = new SqlDataAdapter();sqlDa.SelectCommand = GenerateSelectCommand("id, UserName, linkAdress","Links", "id", "ASC", "1=1", pageIndex, pageSize, conn);DataTable ds = new DataTable();sqlDa.Fill(ds);调用存储过程计算求分页数pageCount = (int)sqlDa.SelectCommand.Parameters["@PageCount"].Value;BindingSource bindseDemo = new BindingSource();bindseDemo.DataSource = ds;dgvDemo.DataSource = bindseDemo;sqlDa.Dispose();// Use SqlDataAdapter Dataset to fetch the data/*DataSet ds = new DataSet();SqlDataAdapter sqlDa = new SqlDataAdapter();sqlDa.SelectCommand = GenerateSelectCommand("fname", "employee", "fname","ASC", "1=1", pageIndex, pageSize, conn);sqlDa.Fill(ds);pageCount = (int)sqlDa.SelectCommand.Parameters["@PageCount"].Value; dgvDemo.DataSource = ds.Tables[0];sqlDa.Dispose();*/conn.Close();}}catch (Exception ex){MessageBox.Show(ex.Message, "Information:", MessageBoxButtons.OK,rmation);}}private void button1_Click(object sender, EventArgs e){//string sqlstr = "select * from Links";//SqlConnection conn = new SqlConnection(connectionString);//DataSet ds = new DataSet();//SqlDataAdapter ada = new SqlDataAdapter(sqlstr, conn);//ada.Fill(ds);//this.dgvDemo.DataSource = ds.Tables[0];}private void bindingNavigatorMoveNextItem_Click_1(object sender, EventArgs e){int currentPage = Convert.ToInt32(bindngrDemo.PositionItem.Text);if (currentPage < pageCount){int page = currentPage + 1;bindngrDemo.PositionItem.Text = page.ToString();LoadData(page, dgvDemo);if (page == pageCount){bindngrDemo.MoveNextItem.Enabled = false;bindngrDemo.MoveLastItem.Enabled = false;}if (page >= 2){bindngrDemo.MovePreviousItem.Enabled = true;bindngrDemo.MoveFirstItem.Enabled = true;}}else{MessageBox.Show("This is the last page", "Information", MessageBoxButtons.OK, rmation);}}private void bindingNavigatorMoveLastItem_Click_1(object sender, EventArgs e){LoadData(pageCount, dgvDemo);bindngrDemo.PositionItem.Text = pageCount.ToString();bindngrDemo.MoveLastItem.Enabled = false;bindngrDemo.MoveNextItem.Enabled = false;bindngrDemo.MovePreviousItem.Enabled = true;bindngrDemo.MoveFirstItem.Enabled = true;}private void bindingNavigatorMovePreviousItem_Click_1(object sender, EventArgs e){int currentPage = Convert.ToInt32(bindngrDemo.PositionItem.Text);if (currentPage >= 2){int page = currentPage - 1;bindngrDemo.PositionItem.Text = page.ToString();LoadData(page, dgvDemo);if (page == 1){bindngrDemo.MovePreviousItem.Enabled = false;bindngrDemo.MoveFirstItem.Enabled = false;}if (page <= pageCount){bindngrDemo.MoveNextItem.Enabled = true;bindngrDemo.MoveLastItem.Enabled = true;}}else{MessageBox.Show("This is the first page", "Information", MessageBoxButtons.OK, rmation);}}private void bindingNavigatorMoveFirstItem_Click_1(object sender, EventArgs e){LoadData(1, dgvDemo);bindngrDemo.PositionItem.Text = "1";bindngrDemo.MoveFirstItem.Enabled = false;bindngrDemo.MovePreviousItem.Enabled = false;bindngrDemo.MoveNextItem.Enabled = true;bindngrDemo.MoveLastItem.Enabled = true;}}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

winform中DataGridView实现分页功能在winform的设计中,要实现对DataGridView控件的分页功能,需要两个控件:BindingSource、BindingNavigator,根据需求可对BindingNavigator进行自由的扩展,下图的示例则是根据一般需求对分页功能的实现。

红色区域是对BindingNavigator控件扩展后的效果。

具体实现过程://窗体构造方法中定义分页所需变量:int pageSize = 0; //每页显示行数int nMax = 0; //总记录数int pageCount = 0; //页数=总记录数/每页显示行数int pageCurrent = 0; //当前页号int nCurrent = 0; //当前记录行DataTable dtInfo = new DataTable(); //存取查询数据结果//分页功能实现public void InitDataSet(){//判断每页显示记录数是否为空,在初始话窗体时为真if (txtRecordNumOfPage.Text.Trim() == ""){try{//pageSize =Convert.ToInt16(ConfigurationManager.AppSettings["PageSize"]); //设置页面行数//读取配置文件中设置的每页显示条数string szConfigFileName = Application.ExecutablePath + ".config"; XmlDocument doc = new XmlDocument();doc.Load(szConfigFileName);XmlNode root = doc.SelectSingleNode("configuration");XmlNode node =root.SelectSingleNode("appSettings/add[@key='PageSize']");XmlElement el = node as XmlElement;pageSize = Convert.ToUInt16(el.GetAttribute("value"));}catch{}if (pageSize == 0){pageSize = 20; //如果读取配置文件失败,则默认将每页显示条数设置为20}txtRecordNumOfPage.Text = pageSize.ToString(); //界面显示的“每页记录数”赋值}else{//读取界面设置的每页显示条数pageSize = Convert.ToUInt16(txtRecordNumOfPage.Text.Trim());}//总记录数赋值nMax = dtInfo.Rows.Count;pageCount = (nMax / pageSize); //采用整除计算页数//判断整除后是否有余数,有则对页数进行+1if ((nMax % pageSize) > 0) pageCount++;pageCurrent = 1; //当前页数从1开始nCurrent = 0; //当前记录数从0开始//调用显示数据方法LoadData();}//显示数据方法private void LoadData(){int nStartPos = 0; //当前页面开始记录行int nEndPos = 0; //当前页面结束记录行//判断查询结果是否为空if (dtInfo.Rows.Count == 0){dgvExperInfo.DataSource = null;return;}else{DataTable dtTemp = dtInfo.Clone(); //克隆DataTable结构,即将字段名称进行复制if (pageCurrent == 1){bindingNavigatorMoveFirstPage.Enabled = false;bindingNavigatorMovePreviousPage.Enabled = false;}else{bindingNavigatorMoveFirstPage.Enabled = true;bindingNavigatorMovePreviousPage.Enabled = true;}if (pageCurrent == pageCount){nEndPos = nMax;bindingNavigatorMoveLastPage.Enabled = false;bindingNavigatorMoveNextPage.Enabled = false;}else{bindingNavigatorMoveLastPage.Enabled = true;bindingNavigatorMoveNextPage.Enabled = true;nEndPos = pageSize * pageCurrent;}nStartPos = nCurrent;lblPageCount.Text = pageCount.ToString(); //界面显示总页数 lblCurrentPage.Text = Convert.ToString(pageCurrent);//当前页数txtCurrentPage.Text = Convert.ToString(pageCurrent);//跳转到页数的显示//从元数据源复制记录行for (int i = nStartPos; i < nEndPos; i++){dtTemp.ImportRow(dtInfo.Rows[i]);nCurrent++;}bdsInfo.DataSource = dtTemp;bdnInfo.BindingSource = bdsInfo;dgvExperInfo.DataSource = bdsInfo;dgvExperInfo.ClearSelection();}}//BindingNavigator控件上的项目点击事件,通过配置各个Item的Text值进行判断执行private void bdnInfo_ItemClicked(object sender, ToolStripItemClickedEventArgs e){if (e.ClickedItem.Text == "上一页"){pageCurrent--;if (pageCurrent <= 0){MessageBox.Show("已经是第一页,请点击“下一页”查看!");pageCurrent++;return;}else{nCurrent = pageSize * (pageCurrent - 1);}LoadData();}if (e.ClickedItem.Text == "下一页"){pageCurrent++;if (pageCurrent > pageCount){MessageBox.Show("已经是最后一页,请点击“上一页”查看!"); pageCurrent--;return;}else{nCurrent=pageSize*(pageCurrent-1);}LoadData();}if (e.ClickedItem.Text == "首页"){pageCurrent = 1;nCurrent = 0;LoadData();}if (e.ClickedItem.Text == "尾页"){pageCurrent = pageCount;nCurrent = pageSize * (pageCurrent - 1);LoadData();}}//跳转页实现private void btnPage_Click(object sender, EventArgs e){if (txtCurrentPage.Text.Trim() != ""){pageCurrent = Convert.ToInt16(txtCurrentPage.Text.Trim());//若输入页号大于最大显示页号,则跳转至最大页if (pageCurrent > pageCount){pageCurrent = pageCount;nCurrent = pageSize * (pageCurrent - 1);}//若输入页号小于1,则跳转至第一页else if (pageCurrent < 1){pageCurrent = 1;nCurrent = 0;LoadData();}//跳转至输入页号else{nCurrent = pageSize * (pageCurrent - 1); //当前行数定位 }//调用加载数据方法LoadData();}}private void txtCurrentPage_TextChanged(object sender, EventArgs e){bool IsNum = true;foreach (char c in txtCurrentPage.Text.Trim()){if (!char.IsNumber(c)) { IsNum = false; break; }}if (IsNum == false){txtCurrentPage.Text = pageCurrent.ToString();}}//当前页回车事件调用跳转页的操作private void txtCurrentPage_KeyPress(object sender, KeyPressEventArgs e) {if (e.KeyChar == 13){btnPage_Click(sender,e);}}//每页显示记录数变更事件private void txtRecordNumOfPage_TextChanged(object sender, EventArgs e) {bool IsNum = true;foreach (char c in txtRecordNumOfPage.Text.Trim()){if (!char.IsNumber(c)) { IsNum = false; break; }}if (IsNum == false){txtRecordNumOfPage.Text = pageSize.ToString();}//判断输入的每页显示条数是否为空或是否为0,输入长度是否大于4位等情况if (txtRecordNumOfPage.Text.Trim() == "" ||Convert.ToUInt32(txtRecordNumOfPage.Text.Trim()) == 0 ||txtRecordNumOfPage.Text.Trim().Length > 4){txtRecordNumOfPage.Text = pageSize.ToString();}//规避了特殊情况后直接调用显示数据方法LoadDocInfoToDGV();}至此,winform中对DataGridView控件的分页功能已经实现,该方法是在网上查了相关资料后参照一些常用的分页效果进行了一些扩展,也在组长的要求下,完善了一些细节上的工作:由于屏幕分辨率的不同,用户可自行对每页显示条数进行设置,设置结果可以在关闭窗体的事件中保存至配置文件,下次进行默认读取;对分页控件中按钮操作的优化,判断是否能够使用的功能,代码中已经进行了体现;另外由于显示器分辨率不尽相同,需要在窗体加载时,设置控件显示的位置,也同样需要代码进行控制。

相关文档
最新文档