Martin Ch
Martin Ch

Reputation: 1367

adding items to combobox

I am trying to add some items to combobox, like its showed on msdn site, but it throws me an null reference exception

 comboBox1.Items.Add("test");

I try to change it on

ComboBox combobox1 = new ComboBox();
object test = new object();
test= "test";
comboBox1.Items.Add(test);

But it didnt works too Can you tell me, where is the problem? Thanks

EDIT: SOLVED : problem was, that I was calling

InitializeComponent();

after this code, not before, now it works as I would like before :)

Upvotes: 3

Views: 10213

Answers (2)

Ed Swangren
Ed Swangren

Reputation: 124790

In this example:

ComboBox combobox1 = new ComboBox();
object test = new object();
test= "test";
comboBox1.Items.Add(test);

Your ComboBox is not a child of any container (i.e., a Form), so it will not be visible in your UI. I assume that's what you meant by "doesn't work" in that case. If you create a control in code you need to add it to your form or a child of your form like so (assuming WinForms, and also that the code is in your Form class...)

Controls.Add( combobox1 );

You will also need to set the size, position it, etc.

The Items collection of a ComboBox should not be null as it is created when you call for it, so we would have to see where combobox1 is coming from. When you are dealing with a simple issue like a NullReferenceException you should use the debugger to find out which object is null.

EDIT: As Manjoor pointed out, combobox1 is not the same as comboBox1 as C# is case sensitive (note the capital B). So, from the evidence you have given us, comboBox1 (capital B) is null.

Upvotes: 3

Manjoor
Manjoor

Reputation: 4199

Replace With

ComboBox combobox1 = new ComboBox();
object test = new object();
test= "test";
combobox1.Items = new ArrayList();
combobox1.Items.Add(test);

combobox1 and comboBox1 is not same

Upvotes: 3

Related Questions