码迷,mamicode.com
首页 > Windows程序 > 详细

C#之数据分页

时间:2016-09-26 13:05:36      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

方法一:临时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#之数据分页

标签:

原文地址:http://www.cnblogs.com/imstrive/p/5908596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!