简体   繁体   中英

How to tell what is the current sort direction of datagridview column?

So, I'm currently working on a datagridview table, with lots of column headers. I want the header text to be "truly" centered (without the sorting icon). So I'm removing sorting ability, and instead writing code so that when the column header is clicked, if it's sorted one way (ascending) to sort it the other way (descending).

Question: Is there a property or easy way to tell how a column is currently sorted? I have both string and integer columns.

   Private Sub CameraTable_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles cameraTable.ColumnHeaderMouseClick

    'in case edits aren't committed
    If cameraTable.IsCurrentRowDirty Or cameraTable.IsCurrentCellInEditMode Then
        cameraTable.CommitEdit(DataGridViewDataErrorContexts.Commit)
    End If

    Dim selectedColumn As DataGridViewColumn = _
    cameraTable.Columns(e.ColumnIndex)

  'pseudo code

     if selectedcolumn.isDesecnding() then 
        cameraTable.Sort(selectedColumn, System.ComponentModel.ListSortDirection.Ascending)
     End if 


End Sub

Since the entire DGV can only ever be sorted by one column or another, you dont need to have a column based LastSort type setting or property. That is, columns are not sorted independent of the grid.

If you are handling the sorts yourself, you should just need to mimic the standard SortedColumn and a SortedOrder properties of the DGV. I am not sure the DGV will update these if you are doing the sort yourself.

 Public Sub SortBy(colIndex As Integer, sortOrd As SortOrder)

      ' if this sort is on a new column, start with ASC
      ' else flip the order
      If colIndex <> SortedColumn Then
          SortedOrder = SortOrder.Asc
      Else
          SortedOrder = If(SortedOrder = SortOrder.Asc, 
                               SortOrder.Desc, SortOrder.Asc)
      End if

      SortedColumn = colIndex

      ' exec the sort
      ApplySort(sortType)
  End Sub

Depending on how you are doing the sort, you may need your own IComparer (s) to handle Text and Value columns. Meanwhile, your code will have to decline to sort Date and Combo Type columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM