Click here to Skip to main content
14,733,076 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Can anyone help me, to implement a quick sort algorithm in datagridview?

I want to sort section "id" column

id name address
11 joni kl
290 lkvan js
829 merry le
91 laun sw

and execute it via the button


What I have tried:

I use code like this, but not sort value 11 and 91

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click


End Sub
Updated 7-Jan-18 8:14am
Patrice T 19-Dec-17 6:57am
'I use code like this, but not sort value 11 and 91'
try to make sentences.
Richard Deeming 19-Dec-17 11:14am
At a guess, you've defined your column as a string, rather than a number.

Several suggestions here: Sorting numerically in a DataGridViewTextBoxColumn[^]
Sinisa Hajnal 20-Dec-17 2:41am
Return sorted data from the data source?
Member 13576502 22-Dec-17 23:35pm

1 solution

If your DataGridView's DataSource property[^] is bound with DataTable, you can sort data this way:

Dim dt As DataTable = DirectCast(DataGridView1.DataSource, DataTable)
'when [id] field is type of integer
'Dim result = dt.AsEnumerable().OrderBy(Function(x) x.Field(Of Integer)("id"))
'when [id] field is type of string
Dim result = dt.AsEnumerable().OrderBy(Function(x) Convert.ToInt32(x.Field(Of String)("id")))

dt = result.CopyToDataTable()
DataGridView1.DataSource = dt

For further details, please see:
Sorting and Filtering Data | Microsoft Docs[^]
How to: Bind Data to the Windows Forms DataGridView Control | Microsoft Docs[^]
DirectCast Operator (Visual Basic) | Microsoft Docs[^]

In case when your DataGridView is not binded with any data source, you can sort DataGridView rows via Linq query.
Dim sortedDGVRows = DataGridView1.Rows. _
    OfType(Of DataGridViewRow)(). _
    OrderBy(Function(r) r.Cells("id"))
DataGridView1.Rows = sortedDgvRows

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900