35

Is there a way to sort a WPF DataGrid programmatically (for example, like if I clicked on my first column)?

Is there a way to simulate this click?

Here is my code:

Collection_Evenements = new ObservableCollection<Evenement>();
 
Collection_Evenements = myEvenement.GetEvenementsForCliCode(App.obj_myClient.m_strCode);
Collection_Evenements.CollectionChanged += Collection_Evenements_CollectionChanged;
myDataGridEvenements.ItemsSource = Collection_Evenements;
 
System.Data.DataView dv = (System.Data.DataView)myDataGridEvenements.ItemsSource;
dv.Sort = "strEvtType";
            
myDataGridEvenements.Focus();
myDataGridEvenements.SelectedIndex = 0;
myDataGridEvenements.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

I don't know why, but the line dv.Sort = "strEvtType"; causes a strange thing, my Window shows up and the program doesn't continue to execute the next lines, nevertheless, I don't see the sort!

2
  • Can't you sort your DataGrid view? And refresh the layout? Commented Jun 6, 2013 at 7:39
  • 1
    have you an example please ? how doing this ? Thanks Commented Jun 6, 2013 at 7:41

7 Answers 7

51

voo's solution was not working for me, ItemsSource was null, most likely because it was not directly set, but bound. All other solutions I found here at StackOverflow were dealing with sorting the Model only, but the DataGrid header was not reflecting to the sort.

Here's a proper solution based on the incomplete script here: http://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}

In case of your code, it can be used like this:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);

Or by using the default parameter values, simply:

SortDataGrid(myDataGridEvenements);
Sign up to request clarification or add additional context in comments.

1 Comment

This does indeed show the soft arrow but that's it. The sort is not actually performed.
8

Get your ItemsSource's DataView and use its Sort property to specify the column you are sorting by:

(yourDataGrid.ItemsSource as DataView).Sort = "NAME_OF_COLUMN";

5 Comments

Hello, thanks for the answer. What's the name of the column, is the "header" property ? I don't found the name property :(
@WalterFabioSimoni No, it is the name of the column of your source, that you bind to your DataGrid.
Ok, understood !Nevertheless when the programme go on the .Sort line, my programme window Show up and thats'all ! It's strange
@WalterFabioSimoni What is the structure of your Evenement type? I suppose you should pass the property name of Evenement, which you want to sort by.
Setting the Sort value doesn't actually sort the data.
6

PerformSort method of the DataGrid is what actually executed on a column's header click. However this method is internal. So if you really want to simulate the click you need to use reflection:

public static void SortColumn(DataGrid dataGrid, int columnIndex)
{
    var performSortMethod = typeof(DataGrid)
                            .GetMethod("PerformSort",
                                       BindingFlags.Instance | BindingFlags.NonPublic);

    performSortMethod?.Invoke(dataGrid, new[] { dataGrid.Columns[columnIndex] });
}

2 Comments

Working like charm, ty :D
This is great! You can also call the DefaultSort method if you for sure don't need to override the sorting.
6

Fast & Easy way:

dgv.Items.SortDescriptions.Clear();
dgv.Items.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Descending));
dgv.Items.Refresh();

Comments

3

This method works for me:

CollectionViewSource.GetDefaultView(dataGrid.ItemsSource).Refresh();

dataGrid.Items.SortDescriptions.Clear();

dataGrid.Items.SortDescriptions.Add(
    new SortDescription(dgEvents.Columns[0].SortMemberPath,
    ListSortDirection.Descending));
                
foreach (var col in dataGrid.Columns)
{
    col.SortDirection = null;
}

dataGrid.Columns[0].SortDirection = ListSortDirection.Descending;

dataGrid.Items.Refresh();

Comments

1

You can use ICollectionView to sort your items in a DataGrid.

 var view = CollectionViewSource.GetDefaultView(this.dataGrid);
 view.SortDescriptions.Add(new SortDescription("MyPropertyToSort", ListSortDirection.Descending));

1 Comment

if you dont bind to a object collection but to a datatable - you have to use IBindingListView.Filter (msdn.microsoft.com/de-de/library/…)
0

To sort your DataGrid like if you clicked on your first column, you have to work on DataView created from WPF. In this exampe the DataGrid is sorted every time that columns are AutoGenerated but you can select other event like DataGrid1_Loaded

using System.Windows.Data;

private void DataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
    {
        (((DataGrid)sender).ItemsSource as DataView).Sort = DataGrid1.Columns[0].Header.ToString();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.