This is a windows forms application. I have a class Program.cs and a form DeployerConsole.cs with a ListBox on it. I am attempting to loop through the results from the SQL query. I am having trouble and getting a ‘Object reference not set to an instance of an object.’ error when I try to access the data and insert it into my listbox on the form.
EDIT: The SQL Query is completing successfully and the Console.WriteLine is outputting to the output window properly with the correct data.
static void LoadServers()
{
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
//DeployerConsole DC = new DeployerConsole();
SqlConnection myConnection = new SqlConnection("server=XXX; database=XXX; uid=XXX; pwd=XXX;Integrated Security=true;Connection Lifetime=5;Trusted_Connection=yes;");
myConnection.Open();
DataSet ds = new DataSet();
SqlCommand myCommand = new SqlCommand("SELECT ServerName FROM DeployServers", myConnection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
Console.WriteLine(dr["ServerName"].ToString());
}
}
EDIT: Added Screenshot

Anyone have any suggestions or provide guidance as to what I am doing wrong?
EDIT (ANSWER): Well, I moved the code from the class to the form. No problems accessing the listBox now. However, I still would like to know the solution to this.
It might be worth a try (just for testing purposes) to try:
That could give you a clue, if which you might need to make sure someplace listBox1 is instantiated.
EDIT
It might be that DC is not being correctly passed by reference to the static method.
It might be better to change the signature of the Method to accept the form.
and call it assuming from the form: