Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi All,

I am using the serial port to connect to a board designed in house. In trying to get it as flexible as possible using user settable parameters it can't have a predetermined serial port (such as Com1) so I am using the below code
C#
private void button4_Click(object sender, EventArgs e)
     {
         string[] ArrayPortNames = null;
         string myComPortName = null;
         int index = -1;

         ArrayPortNames = SerialPort.GetPortNames();
         do
         {
             index += 1;
         } while (!((ArrayPortNames[index] == myComPortName) | (index == ArrayPortNames.GetUpperBound(0))));
         if (index == ArrayPortNames.GetUpperBound(0))
             myComPortName = ArrayPortNames[0];

         for (int i = 0; i < index; i++)
             cboPort.Items.Add(ArrayPortNames[i]);
     }
but can't find any serial ports on the laptop I am using according to device manager there is one Com1 the hardware (it's an old laptop) using a USB to 9 Way converter, which it finds with no action on my part run button4 again it now finds Com1 (and not Com5) as soon as it is removed it can't see Com1 again. Even if I try to use Com1 when it can see it it wont let me open it. I have tried on Windows 7 Thinkpad and it appears to work is the opionon that the PC's serial ports are on the way out ?
Posted

1 solution

I can't figure out the intention of that code fragment but it doesn't look right. Can you explain the use of the do while loop and the variable myComPortName?

I would have just used this (assuming cboPort is a combobox)
C#
private void button4_Click(object sender, EventArgs e)
       {
           cboPort.DataSource = SerialPort.GetPortNames();
       }



Alan.
 
Share this answer
 
Comments
glennPattonWork3 15-Jun-12 11:55am    
Umm, the original intention was to order(Com1, Com3 etc.) the Com port as they re presented rather than get whole lot as .GetPortNames does it tends to group according to the lead number (i.e. Com1, Com14, Com3 etc.), but I appear to have other issues now the Laptop has finally thrown in the towel and won't boot, the think Pad (my first attempt at Win 7) See's three Com Ports only one is present (a USB to serial) are the rest, Sorry this reply been a while I was trying out various methods on a ThinkPad (Win 7) getting lost, found and lost again!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900