How to auto sort datagrid column when binded datatable changes

Viewed 54

I'm facing a problem that i don't know how to solve. Maybe someone can throw some light in my path :)

I am developing an WPF application that has a DataGrid binded to a DataTable using MVVM. I have made it this way because i have to manage a list of drivers and the times they are making in slot races and i don't know how many circuits and how many laps they will race at design time so this info is configured inside the application and the DataTable is generated based on it and because of that I need the columns of the datagrid to be autogenerated.

Here is an example of how it sees at the moment.

Race DataGrid

The problems is that when i receive a new time for a driver the DataTable is updated with the new time, all the TOTALS are recalculated and the info is correctly updated in the DataGrid but I would like that when that happens, the TOTAL column of the DataGrid is automatically sorted showing the driver with the lower TOTAL first.

Any help is appreciated.

Regards.

1 Answers

you can sort DataTable itself with Sort property:

RaceDataTable.DefaultView.Sort = "TOTAL ASC";

make sure that "TOTAL" column has numeric type (double) and DataGrid is bound to DataView (RaceDataTable.DefaultView)

full example (.NET Framework 4.8):

<Window ...>
    <Grid>
        <DataGrid Name="dg"/>
        
        <UniformGrid Rows="1" VerticalAlignment="Bottom">
            <Button Content="RND ALL" Click="UpdateAllClick"/>
            <Button Content="RND ONE" Click="UpdateOneClick"/>
        </UniformGrid>
    </Grid>
</Window>

with code-behind:

using System;
using System.Data;
using System.Windows;

namespace TestProject
{
    public partial class Window1 : Window
    {
        DataTable dt;
        Random rnd = new Random();
        public Window1()
        {
            InitializeComponent();
            
            dt = new DataTable
            {
                Columns =
                {
                    { "ID", typeof(int) },
                    { "TOTAL", typeof(double) },
                },
                DefaultView =
                {
                    Sort = "TOTAL ASC"
                }
            };

            for(int i = 1; i <= 16; i++)
            {
                dt.Rows.Add(i, 0.0);
            }

            dg.ItemsSource = dt.DefaultView;
        }

        private void UpdateAllClick(object sender, RoutedEventArgs e)
        {
            for(int i = 0; i < dt.Rows.Count; i++)
            {
                UpdateRow(i);
            }            
        }

        private void UpdateOneClick(object sender, RoutedEventArgs e)
        {
            UpdateRow(rnd.Next(dt.Rows.Count));
        }

        private void UpdateRow(int idx)
        {
            dt.Rows[idx].SetField<double>("TOTAL", rnd.Next(10000) * 0.1);
        }
    }
}

sorted DataGrid

Related