DataGridView 分頁

     void Query_Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                object[] obj = e.Result as object[];

                if (obj != null)
                {
                    if (obj[0] != null)
                    {

                        dtClone = obj[0] as DataTable;
                        //SetInfo(lbInfo); 
                        PageIndex = 1;
                        SetPageCount(dtClone);
                        LoadData(dtClone, grid_KP);
                        //grid_KP.DataSource = obj[0];  

                    }
                }

            }
        }

        private void Button_Pre_Click(object sender, EventArgs e)
        {
            if (PageIndex<=1)
            {
                MessageBox.Show("已經是第一頁!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            PageIndex--;
            LoadData(dtClone,grid_KP);
           
          
        }

        private void Button_Next_Click(object sender, EventArgs e)
        {
            if (PageIndex >= PageCount)
            {
                MessageBox.Show("已經是最後一頁!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            PageIndex++;
            LoadData(dtClone,grid_KP);
           
        }

        #region
        private int PageCount = 0;//總頁數
        private int PageSize = 10;//每頁記錄顯示條數
        private int PageIndex = 0;//當前頁數 
        private int _Max = 0;
        private DataTable dtClone = null;


        private void SetInfo(Label lb)
        {
            lb.Text = string.Format("當前第{0}頁,總共{1}頁{2}條數據",PageIndex,PageCount,_Max);
        }
        /// <summary>
        /// 設置頁數
        /// </summary>
        /// <param name="dt">源數據</param>
        private void SetPageCount(DataTable dt)
        {

            _Max = dt.Rows.Count;
            PageCount = _Max / PageSize;
            if (_Max % PageSize > 0)
                PageCount++;


        }

        private void LoadData(DataTable dt,DataGridView grid)
        {
            DataTable dtTemp = dt.Clone();
            dtTemp.Clear(); 
            
            for (int i = PageSize * (PageIndex - 1); i <(PageSize * PageIndex < _Max ? PageSize * PageIndex : _Max); i++) 
            {

                dtTemp.ImportRow(dt.Rows[i]);

            } 
            grid.DataSource = dtTemp;
            grid_KP.Columns["物料描述"].Width = 280;
            SetdataGridView(grid_KP);
            SetInfo(lbInfo);

        }


發佈了43 篇原創文章 · 獲贊 1 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章