Hello Daniwebbers

I have a 2 dimentional control array which gets added to it programatically. There's a lot to add to it but i have already stumbled at the first hurdle.
I keep getting the standard "Object reference not set to an instance of an object." error when the first control is added.

Control array is initialised:

Control[ ][ ] TControls = new Control[6][];

Controls are added:

t = 1;

TControls[t][1] = new GroupBox();
TControls[t][1].Visible = false;
TControls[t][1].Parent = gbtasks;
TControls[t][1].Name = "t" + (t + 1).ToString();
TControls[t][1].ForeColor = Color.SeaGreen;
TControls[t][1].Text = (t + 1).ToString();
TControls[t][1].Size = new Size(262, 42);

if (t == 1)
    TControls[t][1].Location = new Point(3, 68);
else
    TControls[t][1].Location = new Point(3, 68 + (43 * (t - 1)));

TControls[t][1].MouseEnter += new EventHandler(TEnter);

thank you very much for your help

You initializes one dimension of the 2D array. You need to initialize each element of that dimension, like so:

TControls[t] = new Control[size];

This is called a jagged array, since each element of the first dimension can have a different length. FYI, C# also has a convention for a rectangular array, like this:

Control[,] TControls = new Control[width, height];

In this case, you don't need to initialize like I mentioned above, since it is handled for you, but it all depends on whether or not your array needs to be jagged or not.

thankyou for the help mmailet

do you mean i need to initialise the first dimension of the array before adding controls to the second?

Pretty much, the first dimension of the array is a groupbox, and the second dimension of the array is all the controls contained within this group box.

Thank you!
I may use a rectangular array.

Well kind of... A 2D array is an array of arrays. So the first dimension is an array of Control[]. That is, the first dimension doesn't hold a control, it holds an array Control[]. I hope that makes sense...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.