程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 分頁控件的實現

分頁控件的實現

編輯:C#入門知識

實現虛擬服務類,提供數據
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PagingDemo {
    public class VitrualModel {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class VitrulModelPage {
        public int RecordCount { get; set; }
        public List<VitrualModel> VitrualModels { get; set; }
    }

    public class VitrualService {
        private List<VitrualModel> list;
  
        public VitrualService(int count) {
            list = new List<VitrualModel>();

            for (int i = 0; i < count; i++) {
                VitrualModel model = new VitrualModel();
                model.ID = i + 1;
                model.Name = getVitrulName(i);
                model.Age = getVitrulAge(i);
                list.Add(model);
            }
        }
  
        public VitrulModelPage GetVitrulModelPage(int first, int last) {
            VitrulModelPage page = new VitrulModelPage();
            page.VitrualModels = list.Where(m => m.ID >= first && m.ID <= last).ToList();
            page.RecordCount = list.Count;
            return page;
        }
  
        private static string getVitrulName(int r) {
            Random random = new Random(r);
            int length = random.Next(4, 8);
            char[] chars = new char[length];
            for (int i = 0; i < chars.Length; i++) {
                chars[i] = (char)random.Next(97, 112);
            }
            return new string(chars);
        }

        private static int getVitrulAge(int r) {
            Random random = new Random(r);
            return random.Next(15, 55);
        }
    }
}
實現分頁控件
設計器
namespace PagingDemo {
    partial class Paging {
        /// <summary>
        /// 必需的設計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 組件設計器生成的代碼

        /// <summary>
        /// 設計器支持所需的方法 - 不要
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent() {
            this.linkFirst = new System.Windows.Forms.LinkLabel();
            this.linkPrevious = new System.Windows.Forms.LinkLabel();
            this.linkNext = new System.Windows.Forms.LinkLabel();
            this.linkLast = new System.Windows.Forms.LinkLabel();
            this.cbxIndex = new System.Windows.Forms.ComboBox();
            this.labelStatus = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // linkFirst
            //
            this.linkFirst.AutoSize = true;
            this.linkFirst.Enabled = false;
            this.linkFirst.Location = new System.Drawing.Point(3, 8);
            this.linkFirst.Name = "linkFirst";
            this.linkFirst.Size = new System.Drawing.Size(29, 12);
            this.linkFirst.TabIndex = 0;
            this.linkFirst.TabStop = true;
            this.linkFirst.Text = "首頁";
            this.linkFirst.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkFirst_LinkClicked);
            //
            // linkPrevious
            //
            this.linkPrevious.AutoSize = true;
            this.linkPrevious.Enabled = false;
            this.linkPrevious.Location = new System.Drawing.Point(38, 8);
            this.linkPrevious.Name = "linkPrevious";
            this.linkPrevious.Size = new System.Drawing.Size(29, 12);
            this.linkPrevious.TabIndex = 1;
            this.linkPrevious.TabStop = true;
            this.linkPrevious.Text = "上頁";
            this.linkPrevious.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkPrevious_LinkClicked);
            //
            // linkNext
            //
            this.linkNext.AutoSize = true;
            this.linkNext.Enabled = false;
            this.linkNext.Location = new System.Drawing.Point(73, 8);
            this.linkNext.Name = "linkNext";
            this.linkNext.Size = new System.Drawing.Size(29, 12);
            this.linkNext.TabIndex = 2;
            this.linkNext.TabStop = true;
            this.linkNext.Text = "下頁";
            this.linkNext.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkNext_LinkClicked);
            //
            // linkLast
            //
            this.linkLast.AutoSize = true;
            this.linkLast.Enabled = false;
            this.linkLast.Location = new System.Drawing.Point(108, 8);
            this.linkLast.Name = "linkLast";
            this.linkLast.Size = new System.Drawing.Size(29, 12);
            this.linkLast.TabIndex = 3;
            this.linkLast.TabStop = true;
            this.linkLast.Text = "尾頁";
            this.linkLast.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLast_LinkClicked);
            //
            // cbxIndex
            //
            this.cbxIndex.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            this.cbxIndex.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
            this.cbxIndex.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbxIndex.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.cbxIndex.FormattingEnabled = true;
            this.cbxIndex.Location = new System.Drawing.Point(212, 5);
            this.cbxIndex.Name = "cbxIndex";
            this.cbxIndex.Size = new System.Drawing.Size(50, 20);
            this.cbxIndex.TabIndex = 4;
            this.cbxIndex.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
            //
            // labelStatus
            //
            this.labelStatus.AutoSize = true;
            this.labelStatus.Location = new System.Drawing.Point(268, 8);
            this.labelStatus.Name = "labelStatus";
            this.labelStatus.Size = new System.Drawing.Size(23, 12);
            this.labelStatus.TabIndex = 5;
            this.labelStatus.Text = "1/1";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(153, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 6;
            this.label1.Text = "當前頁:";
            //
            // Paging
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.label1);
            this.Controls.Add(this.labelStatus);
            this.Controls.Add(this.cbxIndex);
            this.Controls.Add(this.linkLast);
            this.Controls.Add(this.linkNext);
            this.Controls.Add(this.linkPrevious);
            this.Controls.Add(this.linkFirst);
            this.Name = "Paging";
            this.Size = new System.Drawing.Size(306, 28);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.LinkLabel linkFirst;
        private System.Windows.Forms.LinkLabel linkPrevious;
        private System.Windows.Forms.LinkLabel linkNext;
        private System.Windows.Forms.LinkLabel linkLast;
        private System.Windows.Forms.ComboBox cbxIndex;
        private System.Windows.Forms.Label labelStatus;
        private System.Windows.Forms.Label label1;
    }
}
邏輯
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PagingDemo {
    /// <summary>
    /// By Jusfr 2012-4-24, 盜版不究
    /// </summary>
    public partial class Paging : UserControl {
        public event EventHandler PageIndexChanged;

        private bool _initialize = false;
        private int _pageSize = 20;
        private int _recordCount = 0;
        private int _pageIndex = 0;
        private int _pageCount = 1;

        /// <summary>
        /// 獲取或設置頁面容量
        /// </summary>
        public int PageSize {
            get { return _pageSize; }
            set {
                if (_pageSize != value) {
                    OnPageSizeChanging(_pageSize, value);
                    _pageSize = value;
                    OnPageSizeChanged();
                }
            }
        }

        //頁面容量變化,如果已經翻頁,則需要重新計算當前頁碼
        protected void OnPageSizeChanging(int oldSize, int newSize) {
            if (_pageIndex != 0) {
                _pageIndex = _pageIndex * oldSize / newSize;
            }
        }

        //頁面容量變化,ComboxBox需要重新填充
        protected void OnPageSizeChanged() {
            _initialize = true;
            _pageCount = Math.Max(1, (int)Math.Ceiling((double)_recordCount / _pageSize));
            cbxIndex.DataSource = Enumerable.Range(1, _pageCount).ToList();
            cbxIndex.SelectedIndex = _pageIndex;
            _initialize = false;

            labelStatus.Text = String.Format("{0}/{1}", _pageIndex + 1, _pageCount);
            linkFirst.Enabled = _pageIndex != 0;
            linkPrevious.Enabled = _pageIndex != 0;
            linkNext.Enabled = _pageIndex != _pageCount - 1;
            linkLast.Enabled = _pageIndex != _pageCount - 1;
        }

        /// <summary>
        /// 獲取或設置頁面記錄總數
        /// </summary>
        [Browsable(false)]
        public int RecordCount {
            get { return _recordCount; }
            set {
                if (_recordCount != value) {
                    _recordCount = value;
                    OnRecordCountChanged();
                }
            }
        }

        //記錄總數變化,視為數據刷新,重置至起始狀態
        protected void OnRecordCountChanged() {
            _initialize = true;
            _pageCount = Math.Max(1, (int)Math.Ceiling((double)_recordCount / _pageSize));
            cbxIndex.DataSource = Enumerable.Range(1, _pageCount).ToList();
            _initialize = false;
            _pageIndex = 0;

            labelStatus.Text = String.Format("{0}/{1}", _pageIndex + 1, _pageCount);
            linkFirst.Enabled = false;
            linkPrevious.Enabled = false;
            linkNext.Enabled = _pageIndex != _pageCount - 1;
            linkLast.Enabled = _pageIndex != _pageCount - 1;
        }

        /// <summary>
        /// 獲取當前頁碼,從零開始
        /// </summary>
        [Browsable(false)]
        public int PageIndex {
            get { return _pageIndex; }
            private set {
                if (_pageIndex != value) {
                    _pageIndex = value;

                    _initialize = true;
                    cbxIndex.SelectedIndex = _pageIndex;
                    _initialize = false;
                    OnPageIndexChanged(EventArgs.Empty);
                }
            }
        }

        //翻頁了,通知注冊的方法
        protected void OnPageIndexChanged(EventArgs e) {
            labelStatus.Text = String.Format("{0}/{1}", _pageIndex + 1, _pageCount);
            linkFirst.Enabled = _pageIndex != 0;
            linkPrevious.Enabled = _pageIndex != 0;
            linkNext.Enabled = _pageIndex != _pageCount - 1;
            linkLast.Enabled = _pageIndex != _pageCount - 1;

            if (PageIndexChanged != null) {
                PageIndexChanged(this, e);
            }
        }

        /// <summary>
        /// 獲取當前第一條記錄的行號
        /// </summary>
        [Browsable(false)]
        public int FirstRecordNumber {
            get {
                return _pageIndex * _pageSize + 1;
            }
        }

        /// <summary>
        /// 獲取當前最後一條記錄的行號
        /// </summary>
        [Browsable(false)]
        public int LastRecrodNumber {
            get {
                return (_pageIndex + 1) * _pageSize;
            }
        }

        public Paging() {
            InitializeComponent();
            _initialize = true;
            cbxIndex.DataSource = new List<int> { 1 };
        }

        //首頁 www.2cto.com
        private void linkFirst_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            PageIndex = 0;
        }

        //前一頁
        private void linkPrevious_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            PageIndex -= 1;
        }

        //後一頁
        private void linkNext_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            PageIndex += 1;
        }

        //末頁
        private void linkLast_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            PageIndex = _pageCount - 1;
        }

        //ComboBox
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
            if (!_initialize) {
                ComboBox box = sender as ComboBox;
                PageIndex = box.SelectedIndex;
            }
        }
    }
}
Demo
設計器
namespace PagingDemo {
    partial class Form3 {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (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.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.button2 = new System.Windows.Forms.Button();
            this.paging1 = new PagingDemo.Paging();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            //
            // dataGridView1
            //
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(12, 53);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ReadOnly = true;
            this.dataGridView1.RowTemplate.Height = 23;
            this.dataGridView1.Size = new System.Drawing.Size(581, 277);
            this.dataGridView1.TabIndex = 0;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(178, 10);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "設置";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(412, 12);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 21);
            this.textBox1.TabIndex = 3;
            this.textBox1.Text = "45";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(353, 15);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 4;
            this.label1.Text = "記錄總數";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(13, 15);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(53, 12);
            this.label2.TabIndex = 5;
            this.label2.Text = "分頁容量";
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(72, 12);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(100, 21);
            this.textBox2.TabIndex = 6;
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(518, 12);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 7;
            this.button2.Text = "刷新";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // paging1
            //
            this.paging1.Location = new System.Drawing.Point(15, 337);
            this.paging1.Name = "paging1";
            this.paging1.PageSize = 10;
            this.paging1.RecordCount = 0;
            this.paging1.Size = new System.Drawing.Size(306, 28);
            this.paging1.TabIndex = 8;
            this.paging1.PageIndexChanged += new System.EventHandler(this.paging1_PageIndexChanged);
            //
            // Form3
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(605, 376);
            this.Controls.Add(this.paging1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "Form3";
            this.Text = "Form3";
            this.Load += new System.EventHandler(this.Form2_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button button2;
        private Paging paging1;
    }
}邏輯
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PagingDemo {
    public partial class Form3 : Form {

        private VitrualService service;

        public Form3() {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e) {
            textBox2.Text = paging1.PageSize.ToString();
        }

        private void query() {
            try {
                int recordCount = Int32.Parse(textBox1.Text);
                int pageSize = Int32.Parse(textBox2.Text);
                service = new VitrualService(recordCount);
                VitrulModelPage page = service.GetVitrulModelPage(paging1.FirstRecordNumber, paging1.LastRecrodNumber);
                paging1.RecordCount = page.RecordCount;
                dataGridView1.DataSource = page.VitrualModels;
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e) {
            try {
                int pageSize = Int32.Parse(textBox2.Text);
                paging1.PageSize = pageSize;
                //query();
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e) {
            query();
        }

        private void paging1_PageIndexChanged(object sender, EventArgs e) {
            query();
        }
    }
}


摘自  Jusfr.W

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved