0

Im trying to populate a dropdown box in visual studio but i feel like im missing some crucial point.

public partial class Form1 : Form
{
    public Form1()
    {
        GetPortOptions();
        InitializeComponent();
    }               

    private void GetPortOptions()
    {
       string[] comPorts = SerialPort.GetPortNames();
       foreach (string com in comPorts)
           cComPort.Items.Add(com);
    }
    private void btnDisconnect_Click(object sender, EventArgs e)
    {
        SerDisconnect();
    }
    private void BtnConnect_Click(object sender, EventArgs e)
    {
        SerConnect();
    }
}

the cComPort is a combobox i created using visual studio toolbox, but im confused on how a link this code with the combobox i created.

the problem is that is get a exception saying:

An unhandled exception of type 'System.NullReferenceException' occurred in Serial_Monitor.exe
Additional information: Object reference not set to an instance of an object.

5
  • show all your code Commented Sep 29, 2016 at 7:13
  • Also, whats exactly the problem? Commented Sep 29, 2016 at 7:14
  • i didnt want to show alle the code, as most of it just unimplemented functions, but i added the code inside the class Commented Sep 29, 2016 at 7:22
  • the exception happens when i try to run the part of the code where i add items to the Ccomport Commented Sep 29, 2016 at 7:25
  • Could you try to call GetPortOptions method after InitializeComponent method? InitializeComponent is method which initialize user control like cComPort. You are trying add control to this combobox before it is created. Commented Sep 29, 2016 at 7:25

2 Answers 2

3

Problem with the function execution order,InitializeComponent method is to initialize its controls and this need to be always first executed prior to any other function in windows application.

public Form1()
{
    InitializeComponent(); //this need to be always first in windows application
    GetPortOptions();
} 
Sign up to request clarification or add additional context in comments.

1 Comment

this makes sense, my logic was turned in another direction due to thinking that my function was the initialization needed, but i get why the component have to go first.
0

what you feel like messing some crucial point in your code. this code not problem if you want reuse this function ,you better add parameter type of ComboBox

private void GetPortOptions(ComboBox cb)
{
    cb.Item.clear();
    string[] comPorts = SerialPort.GetPortNames();
    foreach (string com in comPorts)
    cb.Items.Add(com);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.