Reputation: 616
I have the following table:
Public table As New DataTable
table.Columns.Add("#", GetType(Integer))
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Exp", GetType(Integer))
table.Columns.Add("HP", GetType(Integer))
table.Columns.Add("At", GetType(Integer))
table.Columns.Add("De", GetType(Integer))
table.Columns.Add("SA", GetType(Integer))
table.Columns.Add("SD", GetType(Integer))
table.Columns.Add("Sp", GetType(Integer))
table.Columns.Add("Tot", GetType(Integer))
table.Rows.Add(1, "One", 64, 0, 0, 0, 1, 0, 0, 1)
table.Rows.Add(2, "Two", 142, 0, 0, 0, 1, 1, 0, 2)
table.Rows.Add(3, "Three", 236, 0, 0, 0, 2, 1, 0, 3)
..........
The table has hundreds of entries.
I would like to populate a combobox with all the entries of the Name
field, sorted either alphabetically or by #
(as defined by the user).
Is there a way to easily do this, e.g. something along the lines of
combobox.Items.AddRange(table.Colums(2))
?
Upvotes: 0
Views: 1352
Reputation: 17855
You can get the required entries using LINQ:
Dim values = table.AsEnumerable().
OrderBy(Function(row) row.Field(Of Integer)("#")).
Select(Function(row) row.Field(Of String)("Name")).
ToArray()
And then add them to you combobox:
combobox.Items.AddRange(values)
Upvotes: 1
Reputation: 2454
In the example below, I assume a Combobox named ComboBox1
located on Sheet1
.
I also assume the table is named Table1
. You will need to adjust as required.
This solution is VBA.
Sub SortedComboFromTableColumn()
Dim rng As Range
With CreateObject("System.Collections.ArrayList")
For Each rng In Range("Table1[Name]")
.Add rng.Value
Next
.Sort
Sheets(1).ComboBox1.List = Application.Transpose(.toarray())
End With
End Sub
Upvotes: 1