0

I have a C# Application with a ComboBox where there user shall be able to select which com port he wants to use. I fill the ComboBox with the available com ports like this:

 string[] strPortsList = SerialPort.GetPortNames();
 Array.Sort(strPortsList);
 Combobos.ItemsSource = strPortsList;

So far this works well. I have a list of COM1, COM2, COM5 and so on. When the user selects a com port I can open it.

The problem now is that the user still needs to know which COM Port is the right one for example for the serial2USB cable. He still needs to go to the device manager and check for the name of the com port that the adapter got.

It would be wonderful if the name of the COM Port would be visible in my drop down list like "COM1 (serial2usb)", "COM2 (NMEA Port)",... Then he could choose the right port without needing the device manager. And when I check for the selected item I just want to have COM1 or COM2 or... as a result.

Is this possible in C# somehow?

mm8
  • 163,881
  • 10
  • 57
  • 88
computermaus
  • 63
  • 2
  • 8

2 Answers2

0

Create a class that represents a Port:

public class Port
{
    public string Name { get; set; }
    public string Desc { get; set; }

    public override string ToString()
    {
        return string.Format("{0} ({1})", Name, Desc);
    }
}

And try this:

List<Port> ports;
using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
{
        string[] portnames = SerialPort.GetPortNames();
        var x = searcher.Get().Cast<ManagementBaseObject>().ToList();
        ports = (from n in portnames
        join p in x on n equals p["DeviceID"].ToString() into np
                    from p in np.DefaultIfEmpty()
                    select new Port() { Name = n, Desc = p != null ? p["Description"].ToString() : string.Empty }).ToList();
}

Combobos.ItemsSource = ports;
Combobos.SelectedValuePath = "Name";

You will need to add a reference to System.Management.dll.

You can then get the selected value in the ComboBox by accessing its SelectedValue property:

string port = Combobos.SelectedValue.ToString();
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    Thank you very much. This is already working pretty good but I have one problem with that: I see only 2 of 4 Com ports. The two COMports from my GPS modul are not visible and the usb2serial adapter isn't visible either – computermaus Sep 18 '17 at 17:54
  • SerialPort.GetPortNames returns 4 port names but you only see 2 in the ComboBox. Is that right? – mm8 Sep 19 '17 at 09:05
  • Modify your code slightly. See my edited answer. Obviously there are no description for the other two ports to be obtained. – mm8 Sep 19 '17 at 14:16
  • this works for me comboBox1.DataSource = new BindingSource(ports, null); comboBox1.DisplayMember = "Name"; – Abdul Rehman Nov 24 '18 at 10:02
0

This worked for me in MVC .NET:

ViewBag.PortaName = new SelectList(ports.ToList(), "Name", "Name");
Brydenr
  • 798
  • 1
  • 19
  • 30
Ruben
  • 139
  • 1
  • 3