0
votes

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?

2

2 Answers

0
votes

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();
0
votes

This worked for me in MVC .NET:

ViewBag.PortaName = new SelectList(ports.ToList(), "Name", "Name");