c# winform 實現分頁查詢

hellwrol發表於2020-12-11

效果如下
在這裡插入圖片描述程式碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
int n = 1;
int size = 1;
private void Form2_Load(object sender, EventArgs e)
{
this.label1.Text = “當前第”+n.ToString()+“頁”;
Getdata();
}
public void Getdata()
{
size =Convert.ToInt32(this.textBox1.Text);
string sql = “select from(select ,rn=ROW_NUMBER()over(order by id asc)from department )as t where t.rn between(@n-1)@size+1 and @n@size”;
SqlParameter[] pr = new SqlParameter[]
{
new SqlParameter("@n", SqlDbType.Int) {Value=n },
new SqlParameter("@size",SqlDbType.Int) { Value=size}
};

        DataTable dt = DbHelper.GetDt(sql,pr);
        this.dataGridView1.DataSource = dt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if(n==1)
        {
            MessageBox.Show("已經是第一頁了");
        }
        else
        {
            n--;
            this.label1.Text = "當前第" + n.ToString() + "頁";
            Getdata();
        }
        
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string sql = "select count(*)from department";
        int i = (int)DbHelper.ExecuteScalar(sql);
        //總條數/每頁個數=總頁數
      
        float x = i % size == 0 ?i/size : i % size + 1;
        if(x==n||size>i)
        {
            MessageBox.Show("這是最後一頁了");
        }
        else
        {
            n++;
            this.label1.Text = "當前第" + n.ToString() + "頁";
            Getdata();
        }
       
    }

    private void textBox1_MouseHover(object sender, EventArgs e)
    {
        n = 1;
        size = Convert.ToInt32(this.textBox1.Text);
        Getdata();
    }


    //private void textBox1_MouseMove(object sender, MouseEventArgs e)
    //{
    //    n = 1;
    //    Getdata();
    //}

    //private void textBox1_ModifiedChanged(object sender, EventArgs e)
    //{
    //    n = 1;
    //    Getdata();
    //}
}

}

相關文章