Summary: Disable sorting after clicking DataGridView columnheader,prevent databound DataGridView from sorting while editing!
problem: I have a databound DataGridView in a WinForms which the user may has sorted by a column. The problem is this:after the user leaves a row after editing a cell in the sorted column, the row is immediately re-sort Ed. This is very disorienting for users and makes editing groups of rows together impossible.
Solution: re-databound When the user start editing, run program, or sorted finish, to does that can disable automatic R E-sorting.ting after a initial sort and then only sort again when the user requests it.
/// <summary>///control state when the program is start or stop, we can re-databound DGV to disable re-sorting/// </summary> Public voidChangestatus (BOOLstatus) {Invoke (ThreadStart)Delegate() {MYDGV. columns["Status"]. SortMode = status? DataGridViewColumnSortMode.Automatic:DataGridViewColumnSortMode.NotSortable;//sorting feature state changes if(status) {MYDGV. Sort (MYDGV. columns["Status"], listsortdirection.ascending);//stop running tasks, auto sort } Else{datagridviewrebindsource (MYDGV);//start running tasks, rebind data after sorting } });}/// <summary>///column Header Click Sort Event--after Columnheadermouseclick to Re-databound DGV to disable re-sorting/// </summary>/// <param name= "Sender" ></param>/// <param name= "E" ></param>Private voidMydgv_columnheadermouseclick (Objectsender, DataGridViewCellMouseEventArgs e) { Switch(MYDGV. SortOrder) { CaseSYSTEM.WINDOWS.FORMS.SORTORDER.NONE:MYDGV. Sort (MYDGV. Columns[e.columnindex], listsortdirection.ascending); Break; CaseSYSTEM.WINDOWS.FORMS.SORTORDER.ASCENDING:MYDGV. Sort (MYDGV. Columns[e.columnindex], listsortdirection.descending); Break; CaseSYSTEM.WINDOWS.FORMS.SORTORDER.DESCENDING:MYDGV. Sort (MYDGV. Columns[e.columnindex], listsortdirection.ascending); Break; } datagridviewrebindsource (MYDGV); //rebind data when sorting is complete}/// <summary>///rebind DGV data Cleanup Auto sort--function:re-databound dgv to disable re-sorting/// </summary>/// <param name= "DGV" ></param> Public voidDatagridviewrebindsource (DataGridView dgv) {DataTable table=NewDataTable (); intDgvcolumnsnum =DGV. Columns.count; intDgvrowsnum =DGV. Rows.Count; //get columns for DataGridView foreach(DataGridViewColumn DGVCinchDGV. Columns) {if(DGVC. Visible && DGVC. Celltype! =typeof(Datagridviewcheckboxcell)) {DataColumn DC=NewDataColumn (); dc. ColumnName=DGVC. DataPropertyName; Table. Columns.Add (DC); } } //gets the row of the DataGridView for(inti =0; i < Dgvrowsnum; i++) {DataRow datarow=table. NewRow (); intj =0; for(j =0; J < Dgvcolumnsnum; J + +) {Datarow[j]=DGV. Rows[i]. CELLS[J]. Value; } table. Rows.Add (DataRow); } DGV. DataSource=table;}
DataGridView How to disable automatic sorting after clicking sort Finish