Sort dataGridView columns in C# ? (Windows Form)

C#WinformsDatagridviewSortingGrid

C# Problem Overview


I have a datagridview that i bind from an sql table, in that dv i have those attributes: Id, Name and Price. When i set the SortMode of the Name Columns to Automatic and i click on the header of this column i can sort this dv based on the first letter of the Name, this way i can order products based on their first letters ( Acumulator, Boat, CocaCola, Engine etc).

Is there a way this thing to happen without clicking the header of the column Name. I am looking some code that will do this job when the form will load.

C# Solutions


Solution 1 - C#

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

Solution 2 - C#

dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);

Solution 3 - C#

You can control the data returned from SQL database by ordering the data returned:

orderby [Name]

If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.

Solution 4 - C#

This one is simplier :)

dataview dataview1; 
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;

Solution 5 - C#

The best way to do this is to sort the list before binding data source.

cars = cars.OrderBy(o => o.year).ThenBy(o => o.color).ToList(); adgCars.DataSource = cars;

Sorry for my bad english.

Solution 6 - C#

Use Datatable.Default.Sort property and then bind it to the datagridview.

Solution 7 - C#

I know 2 solutions to this problem.

1. Sort (DataGridViewColumn column, ListSortDirection direction) function

This function can be used to sort a column alphabetically or numerically or by date in descending or ascending order.

example:

dataGridView.Sort(dataGridView1.Columns[5],ListSortDirection.Ascending);

2. Sort (IComparer comparer) function

This function can be use for all other situations as

Sorting a column with specific order that is different than numeric order (example: sorting an amount that can be negative or positive using only absolute values)

Sorting a column with specific order that is different than alphabetic order (example: sorting a text using case insensitive sort)

Sorting multiples columns as sorting a table using AMOUNT column as first column and DATE column as second column.

VB.Net example:

Private Sub pbSort_Click(sender As Object, e As EventArgs) _ 
    Handles pbSort.Click

    grid.Sort(New AmountDateComparer(Me))
End Sub

Private Class AmountDateComparer : Implements IComparer

    Private frm As FrmSearch

    Public Sub New(frm As FrmSearch)
        Me.frm = frm
    End Sub

    Public Function Compare(x1 As Object, x2 As Object) As Integer _
        Implements IComparer.Compare

        Dim row1 As DataGridViewRow = x1
        Dim row2 As DataGridViewRow = x2

        ' compare AMOUNT values of columns

        Dim nAmount1 = Convert.ToDecimal(row1.Cells(frm.Col_AMOUNT.Index).Value)
        Dim nAmount2 = Convert.ToDecimal(row2.Cells(frm.Col_AMOUNT.Index).Value)

        Dim iCompareResult As Integer 
            = System.Decimal.Compare(nAmount1, nAmount2)

        If iCompareResult = 0 Then
            'compare DATE values of columns
            Dim d1 = Convert.ToDateTime(row1.Cells(frm.Col_DATE.Index).Value)
            Dim d2 = Convert.ToDateTime(row2.Cells(frm.Col_DATE.Index).Value)

            iCompareResult = System.DateTime.Compare(d1, d2)
        End If

        Return iCompareResult
    End Function
End Class

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAXheladiniView Question on Stackoverflow
Solution 1 - C#BFreeView Answer on Stackoverflow
Solution 2 - C#user427483View Answer on Stackoverflow
Solution 3 - C#AhmyView Answer on Stackoverflow
Solution 4 - C#nate wewView Answer on Stackoverflow
Solution 5 - C#Luis MárquezView Answer on Stackoverflow
Solution 6 - C#danishView Answer on Stackoverflow
Solution 7 - C#schlebeView Answer on Stackoverflow