winfrom dataGridView 自定义分页实现

Winfrom 基本处于忘光的阶段.先需要做个winfrom 的软件.然后自己扩展了DataGridView带分页的控件。废话不多说 上图先  

现在一步步实现其效果.

1.添加用户控件 上图即可知道布局以及怎么实现

2.代码如下

  #region 控件属性

        /// <summary>
        /// 页大小
        /// </summary>
        public int PageSize
        {
            get;
            set;
        }
        
        /// <summary>
        /// 总记录数
        /// </summary>
        public int DataSoureCount
        {
            get;
            set;
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int PageCount
        {
            get;
            set;
        } 
        
        /// <summary>
        /// 当前记录行
        /// </summary>
        public int CurrentPageIndex
        {
            get;
            set;
        }

        /// <summary>
        /// 取得或者设置数据控件的自定义列名
        /// </summary>
        public List<string> gdvColHeaderText
        {
            get;
            set;
        }

        /// <summary>
        /// 取得或者设置绑定控件的数据集
        /// </summary>
        public DataTable GetGridDataSoure
        {
            get;
            set;
        }

        /// <summary>
        /// 绑定数据到控件中
        /// </summary>
        public void DataBaind()
        {
            dgv.DataSource = GetGridDataSoure;
            lbSoureCount.Text = DataSoureCount.ToString();
            lbPageCount.Text = this.PageCount.ToString();
            lbPageSize.Text = this.PageSize.ToString();
            lbCurrentPageIndex.Text = this.CurrentPageIndex.ToString();
            DataGridViewStyle(dgv);
            if (gdvColHeaderText != null)
            {
                for (int i = 0; i < gdvColHeaderText.Count; i++)
                {
                    if (dgv.Columns.Count >= i)
                    {
                        dgv.Columns[i].HeaderText = gdvColHeaderText[i];
                    }
                }
            }

            if (IsVisibleFirstCom)
            {
                dgv.Columns[0].Visible = false;
            }
        }
        //新增一列填充空余单元格
        bool tc_column = true;

        /// <summary>
        /// DataGridView样式处理
        /// </summary>
        /// <param name="gridview">DataGridView控件</param>
        /// <param name="tc_column">是否需要添加列</param>
        public void DataGridViewStyle(DataGridView gridview)
        {


            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(211)))), ((int)(((byte)(223)))), ((int)(((byte)(240)))));
            dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Navy;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            gridview.AllowUserToAddRows = false;
           gridview.AllowUserToDeleteRows = false;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightCyan;
            Form f = new System.Windows.Forms.Form();
           gridview.AutoGenerateColumns = false;


            gridview.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
            gridview.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            gridview.EnableHeadersVisualStyles = false;
            gridview.GridColor = System.Drawing.SystemColors.GradientInactiveCaption;
            gridview.ReadOnly = true;
            //gridview.RowHeadersVisible = false;
            gridview.RowTemplate.Height = 28;
            gridview.RowTemplate.ReadOnly = false;
            //标题文字居中
            gridview.ColumnHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;

            //gridview.RowHeadersVisible = false;
            gridview.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            gridview.ColumnHeadersHeight = 30;

            //设置选择单元模式
            gridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            if (tc_column)
            {
                //设置默认填充列自动填充
                DataGridViewTextBoxColumn TextBoxColumn = new DataGridViewTextBoxColumn();
                TextBoxColumn.Name = "";
                TextBoxColumn.HeaderText = "";
                gridview.Columns.Insert(gridview.ColumnCount, TextBoxColumn);
                TextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
                //取消该列排序
                TextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
                tc_column = false;
            }

            //点击立即进入编辑模式
            gridview.EditMode = DataGridViewEditMode.EditOnEnter;
        }


        #endregion

        #region 分页按钮事件

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirstPage_Click(object sender, EventArgs e)
        {
            this.CurrentPageIndex = 0;
            PageChange_Click(sender, e);
            //按钮状态
            btnFirstPage.Enabled = false;
            btnLastPage.Enabled = true;
            btnNextPage.Enabled = true;
            btnPrevPage.Enabled = false;
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            if (this.CurrentPageIndex >= 2)
            {
                btnPrevPage.Enabled = true;
                btnLastPage.Enabled = true;
                btnNextPage.Enabled = true;
                btnPrevPage.Enabled = true;
                this.CurrentPageIndex -= 1;
                PageChange_Click(sender, e);
            }
            else
            {
                btnPrevPage.Enabled = false;
                btnFirstPage.Enabled = false;
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if (this.CurrentPageIndex < this.PageCount)
            {
                btnFirstPage.Enabled = true;
                btnLastPage.Enabled = true;
                btnNextPage.Enabled = true;
                btnPrevPage.Enabled = true;
                this.CurrentPageIndex += 1;
                PageChange_Click(sender, e);
            }
            else
            {
                btnNextPage.Enabled = false;
                btnLastPage.Enabled = false;
            }
        }

        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLastPage_Click(object sender, EventArgs e)
        {
            if (this.CurrentPageIndex < this.PageCount)
            {
                btnLastPage.Enabled = false;
                this.CurrentPageIndex = PageCount;
                PageChange_Click(sender, e);
                btnFirstPage.Enabled = true;
                btnNextPage.Enabled = false;
                btnPrevPage.Enabled = true;
            }
            else
            {
                btnLastPage.Enabled = false;
                btnNextPage.Enabled = false;
            }
        }


        #endregion

        /// <summary>
        /// 页改变的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public delegate void PageChange();

        /// <summary>
        /// 页改变的委托事件
        /// </summary>
        public event EventHandler PageChange_Click;

        /// <summary>
        /// 点击行的事件
        /// </summary>
        public delegate void clickRow();

        /// <summary>
        /// 点击行的委托事件
        /// </summary>
        public event EventHandler dgvRows_Click;

        /// <summary>
        /// 单一值
        /// </summary>
        public string singleValue
        {
            get;
            set;
        }

        /// <summary>
        /// 多值
        /// </summary>
        public string manyValue
        {
            get;
            set;
        }

        /// <summary>
        /// 设置需要取的单一值
        /// </summary>
        public string setSingleValue
        {
            get;
            set;
        }

        /// <summary>
        /// 设置需要取的多值
        /// </summary>
        public string setManyValue
        {
            get;
            set;
        }

        /// <summary>
        /// 设置默认单元格选择行事件为单击 如果为单击则为ture 双击为false
        /// </summary>
        protected bool tableCheck
        {
            get 
            {
                bool isSinlgOrDoubleClick=true;
              ParameterModel tableCheckModel=new ParameterBLL().GetModelByID(100, "23");
              if (tableCheckModel == null)
                  return isSinlgOrDoubleClick;
              else
              isSinlgOrDoubleClick=tableCheckModel.fParValue.ToUpper() == "Y" ? true : false;
              return isSinlgOrDoubleClick;
            }
        }

        /// <summary>
        /// 双击单元格事件发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //如果系统设置的为单击 则不促发双击
            if (tableCheck == true) return;
            if (e.RowIndex <= -1) return;
            if (!string.IsNullOrEmpty(setSingleValue))
            {
                singleValue = dgv.Rows[e.RowIndex].Cells[setSingleValue].Value.ToString();
            }
            else
            {
                string[] keyItem = setManyValue.Split(',');
                string Values = string.Empty;
                foreach (string s in keyItem)
                {
                    Values += dgv.Rows[e.RowIndex].Cells[s].Value.ToString() + ",";
                }
                Values = Values.Remove(Values.LastIndexOf(','));
                manyValue = Values;
            }
            dgvRows_Click(sender, e);
        }

        /// <summary>
        /// 是否隐藏首列的值
        /// </summary>
        public bool IsVisibleFirstCom
        {
            get;
            set;
        }

        /// <summary>
        /// 单击单元格事件发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //如果系统设置的为双击 则不促发单击
            if (tableCheck == false) return;
            if (e.RowIndex <= -1) return;
            if (!string.IsNullOrEmpty(setSingleValue))
            {
                singleValue = dgv.Rows[e.RowIndex].Cells[setSingleValue].Value.ToString();
            }
            else
            {
                string[] keyItem = setManyValue.Split(',');
                string Values = string.Empty;
                foreach (string s in keyItem)
                {
                    Values += dgv.Rows[e.RowIndex].Cells[s].Value.ToString() + ",";
                }
                manyValue = Values.Remove(Values.LastIndexOf(','));
            }
            dgvRows_Click(sender, e);
        }
View Code

3.如何使用

在页面在拖入控件.填充数据如下

 string sqlWhere = " where 1=1 and fState in(0,1) ";

            if (!string.IsNullOrEmpty(txtArtNo.Text))
            {
                sqlWhere += string.Format(" and fArtNo like '%{0}%'", txtArtNo.Text);
            }
            if (!string.IsNullOrEmpty(txtBarCode.Text))
            {
                sqlWhere += string.Format(" and fBarCode like '%{0}%'", txtBarCode.Text);
            }
            if (!string.IsNullOrEmpty(txtItemName.Text))
            {
                sqlWhere += string.Format(" and fItemName like '%{0}%'", txtItemName.Text);
            }
            if (ddlBigClassID.SelectedValue.ToString() != "-100")
            {
                sqlWhere += string.Format(" and fBigClassID = '{0}'", ddlBigClassID.SelectedValue);
            }
            if (ddlMidClassID.SelectedValue != null && ddlMidClassID.SelectedValue .ToString()!= "-100")
            {
                sqlWhere += string.Format(" and fMidClassID = '{0}'", ddlMidClassID.SelectedValue);
            }
            if (ddlSubClassID.SelectedValue != null && ddlSubClassID.SelectedValue.ToString() != "-100")
            {
                sqlWhere += string.Format(" and fSubClassID = '{0}'", ddlSubClassID.SelectedValue);
            }

            ItemBaseBLL bll = new ItemBaseBLL();
            fgivItem.PageSize = 25;
            int CurrentPageIndex = fgivItem.CurrentPageIndex == 0 ? fgivItem.CurrentPageIndex += 1 : fgivItem.CurrentPageIndex += 0;
            fgivItem.CurrentPageIndex = CurrentPageIndex;
            fgivItem.GetGridDataSoure = bll.GetDateSoure(sqlWhere, "fItemID", "fItemID,fBigClassName,fMidClassName,fSubClassName,fItemName,fArtNo,fBarCode,fImportPrice,fSalePrice,fPrice1,fInVeryPrice,fCostPrice,fStateText", fgivItem.PageSize, fgivItem.CurrentPageIndex);
            int totalCount = bll.GetCount(sqlWhere);
            fgivItem.DataSoureCount = totalCount;
            int totalPageNum = (totalCount % fgivItem.PageSize) > 1 ? ((totalCount / fgivItem.PageSize) + 1) : (totalCount / fgivItem.PageSize);
            fgivItem.gdvColHeaderText = new List<string> {"商品编号", "商品大类", "商品中类", "商品小类", "商品名称", "商品货号", "商品条码", "进价", "售价", "活动价", "换购价", "成本价", "状态" };
            fgivItem.PageCount = totalPageNum;
            fgivItem.setSingleValue = "fItemID";
            fgivItem.IsVisibleFirstCom = true;
            fgivItem.DataBaind();
View Code
原文地址:https://www.cnblogs.com/wjbobo/p/3135906.html