bfdbndfnd
bfdbndfnd

Reputation: 45

Sort columns in datagridview

In this topic, I asked how to sort the rows by the sum of the values in the row. The solution was this:

var temp = myDataBaseDataSet.table1.Clone();
myDataBaseDataSet.table1.Rows.Cast<DataRow>()
     .OrderByDescending(x => x.ItemArray.OfType<bool>().Count(b => b == true))
     .ToList().ForEach(x =>
     {
         temp.Rows.Add(x.ItemArray);
     });
this.table1DataGridView.DataSource = temp;

Now there's a new maybe stupid question: how to sort the column like rows in example above? Simply, to change the order of the columns (but save columns values)

I tried to make an application for an example. First I do the sorting in rows as already wrote. Then I need to swap the columns by the sum of the values of the columns and they should be placed in order of descending ( like on screenshot ) Example of what i need

Upvotes: 1

Views: 73

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can first get an ordered list of columns from DataTable based on count of checked items in columns. Then remove corresponding columns from grid and add them in order this way:

var columns = dt.Columns.Cast<DataColumn>()
                .Where(x => x.DataType == typeof(bool))
                .Select(x => new
                {
                    Column = x,
                    Count = dt.Rows.Cast<DataRow>()
                                .Count(r => r.Field<bool>(x) == true)
                }).OrderByDescending(x => x.Count)
                .Select(x => x.Column).ToList();

columns.ForEach(x =>
{
    var column = grid.Columns.Cast<DataGridViewColumn>()
                    .Where(c => c.DataPropertyName == x.ColumnName)
                    .FirstOrDefault();
    if (column != null)
    {
        grid.Columns.Remove(column);
        grid.Columns.Add((DataGridViewColumn)column.Clone());
        column.Dispose();
    }
});

Upvotes: 1

Related Questions