none
Unbound datagridview sorting RRS feed

  • Question

  • I have a datagridview that I am binding to a linq table.  The resulting table is five columns and I am hiding two (columns that are not needed like ID).  The users want to be able to sort clicking on a column header.  I have this code and when I run it, I get an error about and unbound datagrid cannot be sorted.

    System.InvalidOperationException: 'DataGridView control must be bound to an IBindingList object to be sorted.'

    The code is and it breaks on the .Sort function

      

      Dim columnIdx As Integer = e.ColumnIndex
            Dim selectedColumnName As String = dgvAuditResults.Columns(columnIdx).HeaderText
            If dgvAuditResults.Columns(columnIdx).HeaderCell.SortGlyphDirection = SortOrder.None Or
                     dgvAuditResults.Columns(columnIdx).HeaderCell.SortGlyphDirection = SortOrder.Descending Then
                dgvAuditResults.Columns(columnIdx).HeaderCell.SortGlyphDirection = SortOrder.Ascending
                dgvAuditResults.Sort(dgvAuditResults.Columns(columnIdx), ComponentModel.ListSortDirection.Ascending)
            Else
                dgvAuditResults.Columns(columnIdx).HeaderCell.SortGlyphDirection = SortOrder.Descending
                dgvAuditResults.Sort(dgvAuditResults.Columns(columnIdx), ComponentModel.ListSortDirection.Descending)
            End If
    My thought is having to rerun a new sorted linq table based on the selection, but I also need to take into account if it is ASC or DESC.  Is there a simpler way to do this?  Thanks


    Brad Allison

    Thursday, August 15, 2019 12:32 PM

Answers

  • Hello,

    A DataGridView does not provide sorting of unbound columns, see the following post. One thing you could try is to take the current DataGridView DataSource and set the datasource (like a DataTable) to a BindingSource then take the BindingSource which becomes the data source for the DataGridView. Yet another idea is using a SortableBindingList.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, August 15, 2019 1:20 PM
    Moderator