mawburn
mawburn

Reputation: 2346

Visual C# combox1.Items.Add("test"); Error?

When I try to add an item to the combo box, I get:

"NullReferenceException was unhandled" "Object reference not set to an instance of an object."

This happens no matter how I do the code to add to the combobox.

comboBox1.Items.Add("test");

or

try
{
    Parties.Open();
    String test = "SELECT PartyName FROM Parties WHERE PartyID = 4";
    selectParty = new OleDbCommand(test, Parties);
    OleDbDataReader testing = selectParty.ExecuteReader();
    while (testing.Read())
    {
        MessageBox.Show(testing.GetValue(0).ToString());
        comboBox1.SelectedIndex =  comboBox1.Items.Add(testing.GetValue(0).ToString());
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return;
}

(messy code above... frustration!)

I'm pretty new to .NET and C# and I don't understand what is going on here, everything everywhere I go is telling me that my code above should work, but it doesn't. MSDN simply lists:

comboBox1.Items.Add("Text");

Upvotes: 0

Views: 241

Answers (2)

user1335169
user1335169

Reputation: 77

visual studio will add an InitializeComponents() method when the designer is used to modify the UI.

You should have a call to the InitializeComponents() method in your form constructor body. If the code interacts with the controls, you need to put the code after the InitializeComponent call. Any code which doesn't interact with the controls is fine above or below InitializeComponents().

Also if you double click on a control in designer visual studio will create a Form_Load event handler which runs after the form constructor.

Upvotes: 0

nickm
nickm

Reputation: 1775

Where are you trying to add items to the ComboBox?

An exception will be thrown if you are calling the above code before InitializeComponent(); in the form constructor. Or if you are assigning the comboBox elsewhere in code.

Make sure all your code is done AFTER InitializeComponent(), this is the method that calls the code in the designer.

Upvotes: 3

Related Questions