我们如何在Winform中的Datagridview中进行分页

我想在窗口窗体的datagridview中每页显示10条记录,用户必须单击“下一步”按钮以显示下10条记录。DataGridview中是否有一些属性,还是我需要创建一个自定义控件?

我需要做些什么才能做到这一点。

回答:

这是一个简单的工作示例,其中 BindingNavigator GUI控件通过将 BindingSource对象的DataSource设置为IListSource的自定义子类来使用它来识别分页符。(感谢关键人物的回答。)当用户单击“下一页”按钮时,将触发BindingNavigator,bindingSource1_CurrentChanged并且您的代码可以获取所需的记录。说明:

  1. 创建Windows窗体应用程序
  2. 将BindingNavigator,DataGridView和BindingSource拖到窗体上
  3. 用以下代码替换Form1.cs:

    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;

    }

    }

    }

    }

以上是 我们如何在Winform中的Datagridview中进行分页 的全部内容, 来源链接: utcz.com/qa/431475.html

回到顶部