Sha*_*pta 20 c# pagination datagridview custom-controls winforms
我想在窗口表单的datagridview中显示每页10条记录,用户必须单击下一步按钮才能显示下10条记录.是否在DataGridview中有一些属性或者我是否需要创建自定义控件.
我需要做些什么来实现这一目标.
Ric*_*ohr 32
这是一个简单的工作示例,其中
BindingNavigator GUI控件使用
BindingSource对象来识别分页符,方法是将其DataSource设置为IListSource的自定义子类.(感谢关键思想的答案.)当用户单击"下一页"按钮时,BindingNavigator将触发bindingSource1_CurrentChanged,您的代码可以获取所需的记录.说明:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PagedDataGridView
{
public partial class Form1 : Form
{
private const int totalRecords = 43;
private const int pageSize = 10;
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Index" });
bindingNavigator1.BindingSource = bindingSource1;
bindingSource1.CurrentChanged += new System.EventHandler(bindingSource1_CurrentChanged);
bindingSource1.DataSource = new PageOffsetList();
}
private void bindingSource1_CurrentChanged(object sender, EventArgs e)
{
// The desired page has changed, so fetch the page of records using the "Current" offset
int offset = (int)bindingSource1.Current;
var records = new List<Record>();
for (int i = offset; i < offset + pageSize && i < totalRecords; i++)
records.Add(new Record { Index = i });
dataGridView1.DataSource = records;
}
class Record
{
public int Index { get; set; }
}
class PageOffsetList : System.ComponentModel.IListSource
{
public bool ContainsListCollection { get; protected set; }
public System.Collections.IList GetList()
{
// Return a list of page offsets based on "totalRecords" and "pageSize"
var pageOffsets = new List<int>();
for (int offset = 0; offset < totalRecords; offset += pageSize)
pageOffsets.Add(offset);
return pageOffsets;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案:我花了将近一年的时间才找到它,并以此为荣
public class SuperGrid : DataGridView
{
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs = new BindingSource();
BindingList<DataTable> tables = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
DataTable dt = null;
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter )
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += bs_PositionChanged;
bs_PositionChanged(bs, EventArgs.Empty);
}
void bs_PositionChanged(object sender, EventArgs e)
{
this.DataSource = tables[bs.Position];
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用它?将上面的代码添加到项目中,将Supergrid和bindingnavigator控件拖到win表单中.
superGrid1.PageSize = 5;
DataTable dt = DataProvider.ExecuteDt("select * from test order by col");
superGrid1.SetPagedDataSource(dt, bindingNavigator1);
Run Code Online (Sandbox Code Playgroud)
并且您获得了一个带有数据绑定的分页Datagridview而没有太多hastle /
| 归档时间: |
|
| 查看次数: |
70967 次 |
| 最近记录: |