Can't find what you're looking for?

Contact us or post in our forums and we'll help you find an answer.

Implement Excel Like Sorting in C1DataGrid for WPF Edition

Background:

By default, when changes are made to a sorted column resorting is done automatically in C1DataGrid. However in MS-Excel, resorting is not done, so the grid does not sort for modified values. Therefore, how to achieve excel like sorting in C1DataGrid.

Steps to Complete:

1. Handle grid’s BeganEdit event. Inside access the editor and further handle an editor’s event that triggers when its Value change (like ValueChanged event of C1NumericBox).

private void _grid_BeganEdit(object sender, DataGridBeganEditEventArgs e)
{
    if (_grid.DataSourceView.SortDescriptions.Count != 0)
    {
        // do similarly for other columns editing element as well
        if (e.EditingElement.GetType() == typeof(C1NumericBox))   
        {
            (e.EditingElement as C1NumericBox).ValueChanged += Editor_ValueChanged;
        }
    }
}

2. Use editor’s event to store the rows in the order they appear in the grid.

ObservableCollection dataCollection;
private void Editor_ValueChanged(object sender, PropertyChangedEventArgs e)
{
    dataCollection = new ObservableCollection(); 
    foreach (DataGridRow row in _grid.Rows)
    {
        if (row.Type != DataGridRowType.New)
        {
            dataCollection.Add((Employee)row.DataItem);
        }
    }
}

3. Store the rows back in the grid after editing is done. C1DataGrid’s CommittedEdit event can be used for this purpose.

private void dataGrid_CommittedEdit(object sender, DataGridCellEventArgs e)
{
    if(dataCollection!=null)
    {
        dataGrid.ItemsSource = null;
        dataGrid.ItemsSource = dataCollection;
    }
}
Get the Latest Version of WPF Edition
Download the Free Trial Now