关于在winform下DataGrid分页代码

关于在winform下DataGrid分页代码

最近头头要我们用DataGrid显示数据的时候一条一条的显示,当点击了某按钮时,下条记录就出现,也就是一次只显示一条记录,~于是我就想到了用DataGrid分页,当然我们在开发中也遇到了很多问题,特别是细节上的~在这里我要特别感谢我的朋友reficul和Oscar给了我不少帮助~
-------------------------代码-----------------------------------
public int NowPage = 1,PageCount = 1,PageSize = 1;//先定义变量并初始化
private void button1_Click(object sender, System.EventArgs e)//上一页
  {
   NowPage--;
   LoadData(sender,e);
  }
  private void button2_Click(object sender, System.EventArgs e)//下一页
  {
   NowPage++;
   LoadData(sender,e);
  }
  private void LoadData(object sender,System.EventArgs e)
  {
   try
   {
    string conn = "server=.;user id=sa;password=;database=Northwind";//连接数据库,我用的事例数据库是SQL里面的
    //设置数据库连接
    SqlConnection SconnStr = new SqlConnection (conn);
    if(SconnStr.State.ToString()=="Closed")
    {
     SconnStr.Open ();
    }
    SqlCommand Countcmd = new SqlCommand ("select count(*) as co from Employees",SconnStr);//读出总记录数
    SqlDataReader Countdr = Countcmd.ExecuteReader();
    if(Countdr.Read())
    {
     PageCount = Int32.Parse (Countdr["co"].ToString ())/PageSize;//用总记录数除于每页显示的记录数=总页数
     if(Int32.Parse (Countdr["co"].ToString ())%PageSize>0) //取模运算,
     {
      PageCount = PageCount +1;//超过一页的显示数按2页算
     }
     if(PageCount<1)//不足一页显示数的按一页算
     {
      PageCount=1;
     }
    }
    SconnStr.Close ();
    pageinfo.Text ="共"+PageCount+"页\t 第"+NowPage+"页";
    //设置操作数据库命令
    if(NowPage>=PageCount)//如果当前的页面值大于或等于总页面数的话,那么当前页面为最后的页面
    {
     NowPage= PageCount;
    }
    if(NowPage<=1)//如果当前的页面值小于或等于一页面的话,那么当前页面为第一页
    {
     NowPage=1;
    }
    int start = (NowPage-1)*PageSize;//当前页的开始记录是前几页的总记录数的最后一个记录
    string command = "select * from Employees ";//填充数据,并显示
    SqlDataAdapter sda = new SqlDataAdapter ( command,SconnStr);
    DataSet ds = new DataSet ();
    sda.Fill(ds,start,PageSize,"Employees");
    dataGrid1.DataSource = ds.Tables ["Employees"].DefaultView ;
    dataGrid1.SetDataBinding(ds,"Employees");
   }
   catch(Exception err)
   {
    MessageBox.Show(err.Message.ToString());
   }
  }
  private void button3_Click(object sender, System.EventArgs e)//首页
  {
       NowPage= 1;
         LoadData(sender,e);
  }
  private void button4_Click(object sender, System.EventArgs e)//尾页
  {
         NowPage= PageCount;
         LoadData(sender,e);
  }
posted @ 2007-09-18 12:07  大牛博客  阅读(1892)  评论(0编辑  收藏  举报