VB.NET Datagrid Sorting of Numbers

S

simchajoy2000

Hi,

I've got a datagrid that has columns containing numbers but when the
user clicks on the column header to sort - the sort is not placing
numbers in the correct order. For example let's say I have the
following column of number data:

1
2
3
6
7
9
10
15
20
25
etc...

After sorting it appears like this:

1
10
15
2
20
25
3
6
7
9

Is there something I can do to rectify this?? Is the datagrid just not
aware of the datatype of the column? I assumed that it would since
it's being loaded from a database but perhaps that is not the case.

Thanks!

Joy
 
C

Charlie

Hi,

This is happening because you did not set the type of the data that
your data column would use. By default, the column inputs are
considered as string and that is why they are being sorted that way.

To fix your problem, just add the data type when you create the data
column.

(extract from MSDN)

Private Sub AddDataColumn(ByVal myTable As DataTable)
Dim myColumn As DataColumn
Dim myType As System.Type
myType = System.Type.GetType("System.Int32")
myColumn = New DataColumn("id", myType)
' Set various properties.
With myColumn
.AutoIncrement = True
.AutoIncrementSeed = 1
.AutoIncrementStep = 1
.ReadOnly = True
End With
' Add to Columns collection.
myTable.Columns.Add(myColumn)
End Sub


If you create your DataColumn that way, it would sort properly

Hope that helps

Charlie
 
S

simchajoy2000

ok that makes sense but what if the column can also contain strings?
It happens very rarely but it still happens.
 
C

Charlie

I think, in that case, you would get a "Type Missmatched" error when
you pull data out of the database and try to fill up your datatable.

One thing you could also do is to sort the table yourself by creating a
new table and iterate through the old table and parse it the way you
want it into the new table and disable the sort feature for the
datagrid.

Anyway, personally, I don't think it's a good idea to mix up the data
types.

Regards,

Charlie
 
S

simchajoy2000

I agree but unfortunately I have had no choice in this case - it looks
like I will have to do some special handling then - thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top