windowsformsdatagridviewpagination

Binding DataGridView in windows forms to a list<List<T>>


I have a collection of custom objects in format List of List of T , i.e, a List Of list of custom objects. I need to bind this collection to a datagridview control in windows forms, and the number of pages should be equal to the number of inner lists in the outer list. Each page should bind to inner List, that is, List of T. Any idea how this can be achieved ?


Solution

  • Presuming that your nested list has been populated, and in addition to your DataGridView, your form has a Previous and Next button for changing pages: you could use the buttons to change an index which indicates which nested list is to be used as the DataSource.

    public List<List<MyObject>> Pages { get; set; } // Populated elsewhere...
    public int PageIndex { get; set; }
    
    private void ChangePage()
    {
      this.PreviousButton.Enabled = this.PageIndex > 0;
      this.NextButton.Enabled = this.PageIndex < this.Pages.Count - 1;
      this.dataGridView1.DataSource = this.Pages[this.PageIndex];
    }
    
    private void PreviousButton_Click(object sender, EventArgs e)
    {
      this.PageIndex--;
      this.ChangePage();
    }
    
    private void NextButton_Click(object sender, EventArgs e)
    {
      this.PageIndex++;
      this.ChangePage();
    }