Sb.6:自定义分页控件-winform

背景:项目需要查询一个数据信息,并以报表形式展示,网上找了好几个都不太满意,感觉不是很难的东西,所以就写个博客,放个Git连接,方便同志们使用

需求:封装一个控件,具备“上一页”、“下一页”、“首页”、“尾页”按钮,并能够根据当前查询的分页数据显示总共多少页,当前处于第几页。按钮触发后如果符合条件需要切换页面将事件发送出去。

做法:1、新建一个UserControl,插入几个按钮及label,合理布局一下;(布局如下)

2、对四个按钮添加 MouseClick事件,并实现点击业务,代码如下:

        private void Button_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (PageCount == 0) return;
                Button button = (Button)sender;
                int tag = int.Parse(button.Tag.ToString());
                switch (tag)
                {
                    case -2:
                        if (CurrentPageNub == 1 || CurrentPageNub == 0)
                        {
                            return;
                        }
                        CurrentPageNub = 1;
                        break;
                    case -1:
                        if (CurrentPageNub == 1 || CurrentPageNub == 0)
                        {
                            return;
                        }
                        CurrentPageNub -= 1;
                        break;
                    case 1:
                        if (CurrentPageNub == PageCount || CurrentPageNub == 0)
                        {
                            return;
                        }
                        CurrentPageNub += 1;
                        break;
                    case 2:
                        if (CurrentPageNub == PageCount || CurrentPageNub == 0)
                        {
                            return;
                        }
                        CurrentPageNub = PageCount;
                        break;
                    default:
                        break;
                }
                DelCtrlHasChange();
                ShowPageTip();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void ShowPageTip()
        {
            try
            {
                this.Invoke(new Action(() => {
                    this.PageIndex.Text = $"第{CurrentPageNub}页/共{PageCount}页";
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

其中  tag 是前面添加的四个按钮的Tag;

3、DelCtrlHasChange方法是发送控件变化的事件,当页码发生变化的时候通知订阅方;

4、其实就这么简单。

 

posted @ 2023-07-28 11:00  晨耕暮饮  阅读(130)  评论(0)    收藏  举报