views:

422

answers:

2

Hi I've got a DataGridView that has a DataTable as it's Datasource. Whenever I sort a column and then edit a cell, after editing the column, the column autosorts so the recently edited cell is no longer in the viewable area. Is there any way to prevent this auto sort from happening and only sort when I click on the columns?

Many thanks in advance.

Daryn

A: 

I don't know if this works, but it sounds like it might.

Try setting the SortMode of each column (DataGridView.Columns(1).SortMode) to Programmatic or NotSortable when the cell is selected for editing and then set it to Automatic once you've finished editing.

RobS
+1  A: 

I don't think there's a way of preventing the sort, but you can store the row, column, and sort values of the grid before the update and then restore them after the update.

Here's some of the code I use: Friend Sub refreshGrid() Dim row As Integer Dim col As Integer Dim gridCol As Integer Dim gridColsToHide As Integer Dim rowCountOrig As Integer Dim rowCountNew As Integer

 row = dgvReadOnly.CurrentRow.Index
 col = dgvReadOnly.CurrentCell.ColumnIndex
  Dim sortVal As String

  sortVal = _setSource.DefaultView.Sort
  rowCountOrig = _setSource.Rows.Count
  _setSource = _displaySet.displaySetTable
  rowCountNew = _setSource.Rows.Count
  setRowFilter()
  _setSource.DefaultView.Sort = sortVal
  If (rowCountNew > rowCountOrig) Then ' added new row
   row = dgvReadOnly.RowCount - 1   ' new row is at bottom of grid, but skip * row
  End If
 dgvReadOnly.DataSource = Nothing
 dgvReadOnly.DataSource = _setSource
 If row >= dgvReadOnly.RowCount - 1 Then   ' after delete
  row = dgvReadOnly.RowCount - 2
 End If
 If row >= 0 Then  ' if didn't delete all rows matching filter
  dgvReadOnly.CurrentCell = dgvReadOnly(col, row)
 End If
End Sub
Beth