marcuthh
marcuthh

Reputation: 596

C# - Change Location of Custom Control inside GroupBox (returns null reference exception)

I am working on a project where I have designed a custom control, and I am trying to add it to and locate it within a group box.

The steps of initialising and adding the control to the box work fine, but then anything I attempt to move or resize the control causes an exception.

        //initialise using object in outputs collection
        VitalsVisual vitalsVisual = vitalOutputs.getVitalsVisual();
        //add to relevant groupbox
        grpbxIntraOp.Controls.Add(vitalsVisual);
        //change location (coordinates within groupbox)
        vitalsVisual.Location = new Point(249, 256); //THROWS EXCEPTION
        //resize
        vitalsVisual.Size = new Size(494, 342); //THROWS EXCEPTION IF REACHED

All I get on either of the indicated lines is "Object reference not set to an instance of an object". I don't really understand this, as it would point to the VitalsVisual vitalsVisual not being initialised, but the constructor is called and the Controls.Add() command is working. Surely if it had not been initialised, this command would throw the same exception.

Can anybody spot what might be wrong here? Would really appreciate a nudge in the right direction!

Thanks, Mark

Upvotes: 0

Views: 325

Answers (1)

TaW
TaW

Reputation: 54453

Interesting, but that is by design.

Test:

Button button = null;
this.Controls.Add(button);
button.Location = Point.Empty;

This does just the same, i.e. it throws at the last line, not when adding..

So it is allowed trying to add null objectes to a Controls collection.

I wrote 'trying' because the Controls.Add actually fails quietly:

Button button = null;
Console.WriteLine( this.Controls.Count + " controls now.";
this.Controls.Add(button);
Console.WriteLine( "Still " + this.Controls.Count + " controls.";

No changes in the count.

A look at the sources confirms this:

public virtual void Add(Control value) { if (value == null) return; ...

So to sum up: your function surely returns a null object but the error is suppressed. Is it a bug or a feature?

Upvotes: 1

Related Questions