c# 調用存儲過程對數據庫查詢結果進行分頁展示


使用winform的dataGridView控件實現簡單的分頁

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace 分頁
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private int pageIndex = 1; //當前的頁碼
        private int pageSize = 7; //每頁顯示的記錄
        private int pageCount = 0; //總的頁數
        private int recordCount = 0; //總的記錄
        private void Form1_Load(object sender, EventArgs e)
        {
            loadData();
   
        }
        private void loadData()
        {
            //連接字符串
            string constr = "Data source=SZS\\SQLEXPRESS;INITIAL CATALOG=mysql;integrated Security=true";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                string sql = "usp_fenye"; //sql語句變成存儲過程名
                DataTable dt = new DataTable();
                using (SqlDataAdapter sqlData =new SqlDataAdapter(sql, constr))
                {
                    //表示要執行的是存儲過程
                    sqlData.SelectCommand.CommandType = CommandType.StoredProcedure;
                    //增加參數
                    SqlParameter[] pms = new SqlParameter[] {
                        new SqlParameter("@pagesize",SqlDbType.Int){ Value=pageSize},
                        new SqlParameter("@index",SqlDbType.Int){ Value=pageIndex},
                        new SqlParameter("@recordcount",SqlDbType.Int){Direction=ParameterDirection.Output},
                        new SqlParameter("@pagecount",SqlDbType.Int){ Direction=ParameterDirection.Output},
                    };
                    sqlData.SelectCommand.Parameters.AddRange(pms);
                    sqlData.Fill(dt);
                    //獲取輸出的參數
                    label1.Text = pms[2].Value.ToString();
                    recordCount = Convert.ToInt32(label1.Text);
                    label2.Text = pms[3].Value.ToString();
                    pageCount = Convert.ToInt32(label2.Text);
                    label6.Text = pageIndex.ToString();
                    this.dataGridView1.DataSource = dt;

                }

            }

        }
        //上一頁
        private void button1_Click(object sender, EventArgs e)
        {
            if (pageIndex>1)
            {
                pageIndex--;
                loadData();
            }
            
        }
        //下一頁
        private void button2_Click(object sender, EventArgs e)
        {
            if (pageIndex< pageCount)
            {
                pageIndex++;
                loadData();
            }
            
        }
    }
}

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM