C#前端懒加载sqlserver简单代码
时间: 2023-10-05 17:14:54 浏览: 72
以下是C#前端懒加载SQL Server的简单代码:
```
//在窗体中定义全局变量
private int pageIndex = 0; //当前页数
private int pageSize = 10; //每页显示的记录数
private int totalCount = 0; //总记录数
private void Form_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
//连接数据库
string connectionString = "Data Source=.;Initial Catalog=TestDB;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//获取总记录数
string countSql = "SELECT COUNT(*) FROM TestTable";
SqlCommand countCommand = new SqlCommand(countSql, connection);
totalCount = (int)countCommand.ExecuteScalar();
//获取当前页的数据
string dataSql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ID) AS RowNumber, * FROM TestTable) AS T WHERE T.RowNumber > @StartIndex AND T.RowNumber <= @EndIndex";
SqlCommand dataCommand = new SqlCommand(dataSql, connection);
int startIndex = pageIndex * pageSize;
dataCommand.Parameters.AddWithValue("@StartIndex", startIndex);
dataCommand.Parameters.AddWithValue("@EndIndex", startIndex + pageSize);
SqlDataReader reader = dataCommand.ExecuteReader();
//绑定数据到DataGridView
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
reader.Close();
connection.Close();
}
}
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
//判断是否到达底部
if (e.ScrollOrientation == ScrollOrientation.VerticalScroll && e.NewValue == dataGridView1.VerticalScrollBar.Maximum && (pageIndex + 1) * pageSize < totalCount)
{
//更新当前页数并重新绑定数据
pageIndex++;
BindData();
}
}
```
以上代码实现了懒加载的功能,当用户滚动到DataGridView的底部时,会自动加载下一页数据。其中,`BindData()`方法会获取当前页数的数据并绑定到DataGridView,`dataGridView1_Scroll()`方法则是监听滚动事件并在到达底部时更新页数并重新绑定数据。
阅读全文