使用存儲過程實現分頁

--建立存儲過程
create proc usp_userInfo
@pageSize int=7,--每頁顯示條數
@pageIndex int=1,--每頁顯示頁數
@pageCount int output ,--顯示總的條數
@recodNumber int output--顯示總的頁數
as
begin
select
u.id,
u.userName,
u.userPwd,
u.userGander,
u.userAddress
from(select *,rn= ROW_NUMBER() over(order by id) from UserInfo) as u
where u.rn between (@pageIndex-1)*@pageSize+1 and @pageSize*@pageIndex
--計算總的記錄條數
set @pageCount=(select COUNT(*) from UserInfo)
--計算總的頁數
set @recodNumber =CEILING( @pageCount*1.0/@pageSize)
end
--聲明變量
declare @count int, @number int
--查詢存儲過程,給輸出參數賦值
exec usp_userInfo @pageCount=@count output,@recodNumber=@number output
--輸出結果
print @count
print @numbersql

效果如圖所示:數據庫

 

public partial class Form1 : Form
{
  //定義變量
  private int pageSize = 7;//當前顯示的條數
  private int pageIndex = 1;//當前顯示第幾頁
  private int pageCount;//顯示當前總條數
  private int recodNumber;//顯示總的頁數
  public Form1()
  {
    InitializeComponent();
  }數組

  private void Form1_Load(object sender, EventArgs e)
  {
    ListData();
  }ide

  private void ListData()
  {
    //鏈接數據庫
    string sqlconn = "server=.;database=TestDB;uid=sa;pwd=123456";
    DataTable table = new DataTable();
    //數據庫中的存儲過程名稱(usp_userInfo)
  using (SqlDataAdapter adapter = new SqlDataAdapter("usp_userInfo", sqlconn))
  {
    adapter.SelectCommand.CommandType = CommandType.StoredProcedure;//聲明是存儲過程
    SqlParameter[] parameter = new SqlParameter[]
  {
    //第一個參數必須和數據庫中保持一致
    new SqlParameter("@pageSize",SqlDbType.Int){ Value=pageSize},
    new SqlParameter("@pageIndex",SqlDbType.Int){ Value=pageIndex},
    new SqlParameter("@pageCount", SqlDbType.Int){ Direction=ParameterDirection.Output },//在數據庫中是輸出參數,因此這裏不能用Value,必須用                Direction=ParameterDirection.Output(表示輸出)
    new SqlParameter("@recodNumber", SqlDbType.Int){ Direction=ParameterDirection.Output },ui

  };
    adapter.SelectCommand.Parameters.AddRange(parameter);
    adapter.Fill(table);
    //根據parameter數組的下標取到值
    pageCount = int.Parse(parameter[2].Value.ToString());
    recodNumber = int.Parse(parameter[3].Value.ToString());
    label1.Text = "總條數:" + pageCount.ToString();
    label2.Text = "總頁數:" + recodNumber.ToString();
    label3.Text = "當前頁數:" + pageIndex;
    //綁定數據源
    this.dataGridView1.DataSource = table;this

  }
}spa

  //下一頁orm

  private void button1_Click(object sender, EventArgs e)
  {
    if (pageIndex == recodNumber)
    {
      this.button1.Hide();
    }
    else
    {
      this.button1.Show();
      this.button2.Show();
      pageIndex++;
      ListData();
    }server

  }blog

    //上一頁

    private void button2_Click(object sender, EventArgs e)     {       if (pageIndex == 1)       {         this.button2.Hide();       }       else       {         this.button2.Show();         this.button1.Show();         pageIndex--;         ListData();       }     } }

相關文章
相關標籤/搜索