This is how we solved theproblem withautomatic sorting after editing/adding records to a DataGridView.
We created a new column on the table, called 'Index', and then added it as a hidden, boundcolumn on the DataGridView.After everyprogrammatic sort,we reset the values in that column to reflect the current sort order.We then programmatically sort by the 'Index' column. This way thedatagridview is actually sorted bycolumn who's header was clicked, but editing and adding records to the datagridwill only automatically resort the 'Index'column, which will not change until the next column header is clicked.
Here is the code:
private
DataGridViewColumn currentSortColumn;
private string currentSortColumnName;
private string currentSortDirection = "ASC";
private void lineItemDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
currentSortColumn = lineItemDataGridView.Columns[e.ColumnIndex];
SortOrder sortOrder = lineItemDataGridView.SortOrder;
String columnName = currentSortColumn.DataPropertyName;
//Set the sortColumn and sortDirection variables.
if (currentSortColumnName == columnName)
currentSortDirection = (currentSortDirection ==
"ASC" ? "DESC" : "ASC");
else
currentSortDirection =
"ASC";
currentSortColumnName = columnName;
//Perform the sort
myBindingSource.Sort = currentSortColumnName +
" " + currentSortDirection;
//We need tostopany events from firing as we change the values in the 'Index' column.
bindUnbindDataTables(
false);
//Set the "Index" column to match whatever we just sorted by
if (columnName != "Index")
{
foreach (DataGridViewRow lineItemRow in lineItemDataGridView.Rows)
{
myBindingSource.Position = lineItemRow.Index;
lineItemDataGridView.Rows[lineItemRow.Index].Cells[
"_Index"].Value = lineItemRow.Index;
}
}
bindUnbindDataTables(
true);
//Re-Sort by the "Index" column (which will match the sort order we are currently in)
myBindingSource.Sort =
"Index";
lineItemDataGridView.ClearSelection();
lineItemDataGridView[0, 0].Selected =
true;
lineItemDataGridView.FirstDisplayedScrollingRowIndex = 0;
lineItemDataGridView.ResumeLayout();
//Set the Glyph on the Column we have sorted by (this has to come after the 'Index' column sort or the Glyph disappears)
currentSortColumn.HeaderCell.SortGlyphDirection = (currentSortDirection ==
"ASC" ? SortOrder.Ascending : SortOrder.Descending);
}