Reputation: 6778
I've got this code which populates a SharpLibrary.WinControls.ListBoxEx
Dim MyListBox As SharpLibrary.WinControls.ListBoxEx
Private dataTable As System.Data.DataTable
dataTable = GetNames ' Function that returns a DataTable
MyListBox.Items.Clear()
For count = 0 To dataTable.Rows.Count - 1
MyListBox.Items.Add(dataTable.Rows(count)("Name"))
Next
SharpLibrary is apparently some ancient graphical component API.
I want the data to be presented in alphabetical order. Is it possible to sort a DataTable
?
Edit: Another Solution:
dataTable = GetNames ' Function that returns a DataTable
dataTable.DefaultView.Sort = "Name"
MyListBox.Items.Clear()
For count = 0 To dataTable.Rows.Count - 1
MyListBox.Items.Add(dataTable.DefaultView.Item(count)("Name"))
Next
Upvotes: 0
Views: 6646
Reputation: 1423
You'll want to sort the values in the datatable before you add the items to the listbox.
Assuming you have Linq available in your project its pretty simple.
Dim MyListBox As SharpLibrary.WinControls.ListBoxEx
Private dataTable As System.Data.DataTable
dataTable = GetNames ' Function that returns a DataTable
Dim temp = From r In dataTable Order By r.item("Name") select r
MyListBox.Items.Clear()
If temp IsNot Nothing AndAlso temp.Any Then
For count = 0 To temp.Count - 1
MyListBox.Items.Add(temp(count)("Name"))
Next
End If
This would be even easier if you were using a strongly typed datatable that is part of a dataset but that is beyond the scope of your question.
Upvotes: 2
Reputation: 1613
You need to use DataView
for this.
Dim datav As New DataView
datav = dt.DefaultView
datav.Sort = "ColumnName DESC"
where dt
= datatable that you get from getNames()
.
finally, do this to convert it again to datatable datatype.
dt = datav.ToTable()
Final code is
Dim datav As New DataView
datav = dt.DefaultView
datav.Sort = "ColumnName DESC" 'or ASC, or anything just search for dataview.
dt = datav.ToTable()
Upvotes: 0
Reputation: 2613
This link is likely to help you: http://msdn.microsoft.com/en-us/library/73kk32zz(v=vs.110).aspx
Edit:
Dim view As DataView = table.DefaultView
view.Sort = "LastName, FirstName"
view.RowFilter = "LastName > 'M'"
PrintTableOrView(view, "Current Values in View")
' Create a new DataTable based on the DataView,
' requesting only two columns with distinct values
' in the columns.
Dim newTable As DataTable = view.ToTable("UniqueLastNames", True, "FirstName", "LastName")
This is the part where I believe it was done in the code.
I don't really know VB but its not too hard because the C# code is right underneath, I figure they ought to be really similar in meaning.
Upvotes: 0