How to sort, order, add column to DataTable and define Data Type of column. Also Sorting a DataTable column using a DataView

Dim dt As New DataTable
If userZip <> "" And userRadius <> "" Then
                userzipLat = getLatitude(userZip)
                userzipLong = getLongitude(userZip)
                dt = SQL2DataTable(DistLatLon_sql)
'the following code is highlighted because it demonstrates how to define a new column for a 'DataTable with a defined data type. When a column is added and not defined is assumed as 'a string which cannot be sorted properly if your data is not really strings.
                Dim colDecimalDistance As DataColumn = New DataColumn("distance")
                colDecimalDistance.DataType = System.Type.GetType("System.Decimal")
                If dt.Rows.Count > 0 Then
                    For Each rw As DataRow In dt.Rows
                        distLat = rw.Item("Latitude")
                        distLong = rw.Item("Longitude")
                        rw.Item("distance") = Math.Round(getDistance(userzipLat, userzipLong, distLat, distLong), 1)
                End If
            End If
 'We can sort a DataTable by adding it to a view and then using the view class's Sort 'method. The 'ToTable method of the DataView class let's us easily return the view to a DataTable.
'Note* This is not the only way to sort columns in DataTables...but simple
            Dim view As New DataView(dt)
            view.Sort = "distance ASC"
            'now reset dt to the distance ordered datatable
            dt = view.ToTable()
Tags: Sorting
Last update:
2014-11-12 16:23
Average rating:0 (0 Votes)

You cannot comment on this entry

Chuck Norris has counted to infinity. Twice.

Records in this category