关于数据库存储过程分页DatagridView BindingNavigator 控件的详细实现

关于数据库存储过程分页DatagridView BindingNavigator 控件的详细实现程序有3个控件BindingNavigator:就是DataGridView控件上面的那个,在工程里名字:bindngrDemoDataGridView:dgvDemoBindingSource:这个其实可以不要bindseDemo 示例采用的是SQLSERVER的示例数据库pub在pub数据库里写入分页存储过程CREATEPROCEDURE[db…

大家好,又见面了,我是你们的朋友全栈君。

Untitled

程序有3个控件

BindingNavigator: 就是DataGridView控件上面的那个,在工程里名字: bindngrDemo

DataGridView: dgvDemo

BindingSource: 这个其实可以不要 bindseDemo

 

示例采用的是SQL SERVER的示例数据库pub

在pub数据库里写入分页存储过程

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
AS
BEGIN
DECLARE @SqlRecordCount NVARCHAR(100) -- The SQL Statement to get the total count of the records
DECLARE @SqlSelect NVARCHAR(1000) -- The SQL SELECT statment
SET @SqlRecordCount = N'SELECT @RecordCount = COUNT(*) FROM ' + @Tablename + ' WHERE ' +@Where
DECLARE @RecordCount INT
EXEC sp_executesql @SqlRecordCount, N'@RecordCount INT OUTPUT',@RecordCount OUTPUT -- Transfer the parameter dynamic

IF(@RecordCount % @PageSize = 0)
SET @PageCount = @RecordCount / @PageSize
ELSE
SET @PageCount = @RecordCount / @PageSize + 1

SET @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

 

下面的就是VS里的代码了:

在工程里定义几个变量:

 public partial class frmDataPagination : Form
    {

        #region Define the page size
        static int pageSize = 20;
        static int pageCount = 0;
        #endregion
        ...
    }

上面2个变量,一个定义在数据库里分页时,每页的大小; 另一个用来接收存储过程分页时,输出的总页数。

 

在里面加入一个产生Select命令的函数,用于向sqlDataAdapter传递sql command.

        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);
            sqlcmd.CommandType = 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;
        }

 

下面是LoadData函数, 在这个函数里面可以指定自己要选的table 以及列等等参数

里面有2种数据绑定

可以直接用sql command + Sql datareader

也可以sqldataAdapter + Dataset 或者Datatable

        // Load the page data
        private static void LoadData(int pageIndex, DataGridView dgvDemo)
        {
            string strConn = "server = (local); Database = pubs; Integrated Security = SSPI";
            try
            {
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    conn.Open();   

                    // Use sqlcommand to fetch the data
                    /*
                    SqlCommand cmd = GenerateSelectCommand("fname", "employee", "fname", "ASC", "1=1", pageIndex, pageSize, conn);
                    SqlDataReader rdr = cmd.ExecuteReader();                    
                    BindingSource bindseDemo = new BindingSource();
                    bindseDemo.DataSource = rdr;
                    dgvDemo.DataSource = bindseDemo;
                    */

                    // Use SqlDataAdapter to fetch the data                 
                    SqlDataAdapter sqlDa = new SqlDataAdapter();                  
                    sqlDa.SelectCommand = GenerateSelectCommand("fname, lname, hire_date", "employee", "fname", "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, MessageBoxIcon.Information);
            }
        }

 

窗体Load的代码

private void frmDataPagination_Load(object sender, EventArgs e)
        {
            // Even if there is no records, there is no exception            
            LoadData(1, dgvDemo);

            // Set the status of the BindingNavigator control
            if (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 = "of {" + pageCount.ToString() + "}";
            }    
        }

 

BindingNavigator控件的几个事件

包括4个键

向后,最后,向前,最前

        private void bindingNavigatorMoveNextItem_Click(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, MessageBoxIcon.Information);                   
            }
                
        }

        private void bindingNavigatorMovePreviousItem_Click(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, MessageBoxIcon.Information);
            }

        }

        private void bindingNavigatorMoveLastItem_Click(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 bindingNavigatorMoveFirstItem_Click(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;
        }
    }

 

 

至此就全部完了,里面其他的部分就由自己编写了,比如DataGridView控件的显示等等

 

https://www.cnblogs.com/herbert/archive/2010/07/26/1785445.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/158073.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Java获取二维数组行列长度「建议收藏」

    Java获取二维数组行列长度「建议收藏」二维数组intarray[][]=newint[3][3];行长度:array.length列长度:array[i].lengthclassTest{for(inti=0;i

  • size_t和int区别

    size_t和int区别size_t和intsize_t是一些C/C++标准在stddef.h中定义的。这个类型足以用来表示对象的大小。size_t的真实类型与操作系统有关。在32位架构中被普遍定义为:typedefunsignedintsize_t;而在64位架构中被定义为:typedefunsignedlongsize_t;size_t在32位架构上…

  • iframe 透明兼容,设置iframe透明背景的方法「建议收藏」

    iframe 透明兼容,设置iframe透明背景的方法「建议收藏」从IE5.5+就支持iframe框架的背景透明。通过使用allowtransparency和background-color来设置iframe框架的透明效果,代码如下:1<iframesr

  • 业务逻辑漏洞

    业务逻辑漏洞目录什么是业务逻辑漏洞:业务逻辑漏洞产生的核心原因:应用中的缺陷通常分为两种类型:逻辑漏洞主要产生的位置登录处存在的逻辑漏洞1.可以暴力破解用户名或密码:2.session没有清空:业务办理处存在的逻辑漏洞水平越权篡改手机号验证码处存在的逻辑漏洞登录验证码未刷新手机或邮箱验证码可爆破手机或邮箱验证码回显到客户端修改response包绕过判定支付处存在的逻辑漏洞修改商品编号金额修改商品数量修改通过前端限制限购商品充值中放弃订单

  • windows 显示进程的命令 TASKLIST 详解

    windows 显示进程的命令 TASKLIST 详解用jstat查看jvm内存的使用的情况时,因为是windows机器,不能使用top命令方便的查出来,进程好在网上搜了一下看到了在windows原来使用的是tasklist特意将tasklist的用法记录下来。原帖的地址是:http://hi.baidu.com/lgh_boffin/blog/item/314b1194fb957c18d21b70b6.html“Taskli

  • 最简单的vue上传图片

    最简单的vue上传图片