Claudi Claudi - 2 months ago 8
C# Question

Adding string array to existing combobox

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.

Answer

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();
}