Olivier de Rivoyre
Olivier de Rivoyre

Reputation: 1597

How to set the default Sort on a DevExpress GridView

On .net WinForm, DevExpress's GridControl/GridView bound on a DataSet, how to specify the default sort order? The one that is used when there is no visible GridColumn with a SortOrder.

By default, I have set a sorting on the view on my hidden DateTimeStamp GridColumn. It is of course overrided by user if user click on a column. User can "Clear Sorting" using the menu on column or by clicking on a column while pressing the Control key. When doing that, Rows are not sorted anymore (or maybe by PK?) while I would like them sorted by DateTimeStamp.

Any idea? Maybe by plugging code to be notified when user "Clear Sorting"? I can play with GridView.PopupMenuShowing and GridStringId.MenuColumnClearSorting to handle the user-click-on-menu case. But it does not handle the case of Control+click.

Has someone meet the same problem and found a (simple) solution?

Upvotes: 4

Views: 19905

Answers (6)

knoami
knoami

Reputation: 605

As per this answer in Devexpress support center How to sort GridView multiple columns programmatically?

The following code can be used for this purpose:

<your GridView>.SortInfo.AddRange(new DevExpress.XtraGrid.Columns.GridColumnSortInfo[] {  
       new DevExpress.XtraGrid.Columns.GridColumnSortInfo(<your first GridColumn>, DevExpress.Data.ColumnSortOrder.Ascending),  
       new DevExpress.XtraGrid.Columns.GridColumnSortInfo(<your second GridColumn>, DevExpress.Data.ColumnSortOrder.Ascending)});  

More details can be found at Sorting in Code

Upvotes: 0

Amilkar Ferr&#225;
Amilkar Ferr&#225;

Reputation: 11

Just put this after InitializeComponent(); on constructor

GridView1.Columns["FieldName"].SortOrder = ColumnSortOrder.Ascending;

Upvotes: 1

Bernt
Bernt

Reputation: 1

GridControl.SortBy(DateTimeStampColumn, ColumnSortOrder.Descending);

Upvotes: -3

DevExpress Team
DevExpress Team

Reputation: 11376

If I were you, I would sort the grid's DataSource based on the required column. In this case, if the gridView's sorting condition is cleared by the end-user, data will be displayed in the order specified by your DataSource.

UPDATE here is the code which should work for you:

DataView dv = yourDataTable.DefaultView;
dv.Sort = "SomeField";
gridControl.DataSource = dv;

Also, take a look at the following MSDN article :

DataView.Sort Property

Upvotes: 2

user528573
user528573

Reputation: 143

Would it not be easiest just to disable end-user sorting? Or have I misunderstood your problem - i.e. do you want their sorting to be applied after your default sorting?

Upvotes: 1

Ivan Ferić
Ivan Ferić

Reputation: 4763

You could add event handler on GridView.EndSorting event, and in that handler check if there are any columns which have SortIndex >= 0. If there are not, you could set your own sorting.

Upvotes: 0

Related Questions