0

I have a combo box in which all serial ports should be listed. I have this functionality. Now I just want to sort it. Combobox contents order:

Before sorting:

COM3

COM1

COM9

COM10

I've tried to make it with

Combobox.Sorted = True

but then COM10 is at the 2nd position. How can I solve it to make it look like this?

COM1

COM3

COM9

COM10

I want that without ICompare. A Sub will be not bad.

My Code for filling the Combobox:

 For Each sp As String In My.Computer.Ports.SerialPortNames
         cmbComPort.Items.Add(sp)
         cmbComPort.Sorted = True
 Next
a.b_om
  • 91
  • 9

1 Answers1

1

Instead of directly populating the items of the combobox, you can make a List, order that, and assign it as the DataSource of the combobox, like this:

Sub PopulateComPorts()
    Dim ports As String() = IO.Ports.SerialPort.GetPortNames()
    Dim sortedPorts = ports.OrderBy(Function(p) CInt(p.Substring(3))).ToList()
    ComboBox1.DataSource = sortedPorts

End Sub

Note that that sort is only for strings having an integer starting after three characters, such as "COM1", "COM10", "LPT2", etc. For the general case, Sorting an array of folder names like Windows Explorer (Numerically and Alphabetically) shows how to use a Windows function to do the sort.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Yes. That was it. Thank you Andrew Morton. Can you please remove the duplication node, because it's not anymore one. – a.b_om Sep 25 '19 at 11:13