首页 > 代码库 > C#之数据分页

C#之数据分页

方法一:临时datatable

创建临时表,临时变量

1 DataTable dt = null;             //临时表2 private int _pageCount = 0;      //总分页数3 private int _currentPage = 1;    //当前页数4 private int _itemsCount = 20;    //每页的数量

加载数据到临时表,该方法测试放到了窗体的Load事件中(‘###’表示关键词)

 1     string strConn = @"Data Source=LONG-PC\;Initial Catalog=###;User ID=long;password=###"; 2     SqlConnection conn = new SqlConnection(strConn); 3     conn.Open(); 4  5     SqlCommand cmd = new SqlCommand(); 6     cmd.Connection = conn; 7     cmd.CommandText = "select * from ###"; 8     cmd.CommandType = CommandType.Text; 9     cmd.ExecuteNonQuery();10 11     SqlDataAdapter adap = new SqlDataAdapter(cmd);12     dt = new DataTable();13     adap.Fill(dt);14 15     int rowNumber = dt.Rows.Count;16     _pageCount = rowNumber / _itemsCount;17     if (rowNumber % _itemsCount != 0)18     {19         _pageCount++;20     }21     LoadContents(dt, 1);

上一页:

1     _currentPage--;2     if (_currentPage <= 0)3         _currentPage = 1;4     LoadContents(dt, _currentPage);

下一页:

1     _currentPage++;2     if (_currentPage >= _pageCount)3         _currentPage = _pageCount;4     LoadContents(dt, _currentPage);

加载的方法:

 1    private void LoadContents(DataTable dt, int currentPage) 2    { 3        DataTable temp = dt.Clone(); 4        for (int i = 0; i < _itemsCount; i++) 5        {  6            int rowNumber=(currentPage-1)*_itemsCount+i; 7            temp.ImportRow(dt.Rows[rowNumber]); 8        } 9 10        dataGridView1.DataSource = temp;11    }

 

C#之数据分页