array of combo boxes

  • Thread starter Thread starter Jessica
  • Start date Start date
J

Jessica

Hi,

I am new to C# and would like to get some help. I tried creating an
array of comboboxes in my form (the same way as if I am initializing
an array of built-in types) but got this error: "Cannot apply indexing
with [] to an expression of type 'System.Windows.Forms.ComboBox'"

This is what I did:

In declaration:

private System.Windows.Forms.ComboBox[] combos;


Then later I initialize it:

int num_combo = 3;
this.combos = new System.Windows.Forms.ComboBox[num_combo];

for (int i = 0; i < num_combo; i++)
this.combos.Location = ....


Thanks for your help!

Jessica
 
Hi Jessica,

ComboBox[] isn't really an array of ComboBox, it's an array of ComboBox references.
When you intialize it with new ComboBox[num_combo] you are actually filling it with 3 ComboBox references that will be empty (null).

As Trebek said you need to assign a ComboBox object to each of these references before you can use them.
for(int i = 0; i < num_combo; i++)
{
combos = new ComboBox(); // create a new ComboBox object and store the reference
}

However, your code should produce a NullReferenceException at run time "Object Reference not set to an instance of an object". I suspect your orginial code had a typo in the line of

System.Windows.Forms.ComboBox combos; // note the missing []
combos = new System.Windows.Forms.ComboBox[num_combos];
 
Back
Top