I'm creating a Windows form where it should list the COM Ports on my PC. I'm trying to add this data to a ComBox, where it will list/display all my COM Ports and the details of each one. This is the code.
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
{
var portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());
var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
foreach (string s in portList)
{
cb1.Text = s;
}
}
}
This code works perfectly in a Console App, it shows exactly what I need. But in the Windows Form, it is not working. I have googled some possible solutions for this, but none of them worked. I am not an expert on that, but I believe this error could be something related with the Data Bindings, I tried to remove the Data Bindings but I couldn't.
cb1.DataSource = null; or cb1.Items.Clear();
These were just two of many things that I tried but none worked.
You are currently not adding any items to the ComboBox. Check out the modified code.
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
{
var portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());
var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
foreach (string s in portList)
{
cb1.Items.Add(s); //THIS LINE CHANGED
}
}
}
You want to add the available COM Ports to the ComboBox so you have to add a new Item for every COM Port. This items can be selected by the user after they are inserted.
EDIT: To run the code when opening your form you should do something like this:
public Form1() {
InitializeComponent();
using(var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'")) {
var portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p ["Caption"]
.ToString());
var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
foreach (string s in portList) {
cb1.Items.Add(s); // THIS LINE CHANGED
}
}
}