Badmiral
Badmiral

Reputation: 1589

Null reference error when adding picturebox dynamically to tabpage

Getting the exception message:

Object Reference not set to an instance of an object.

My code is:

PictureBox myPicBox = new PictureBox();
myPicBox.Visible = true;
myPicBox.Image = Bitmap.FromFile(@"C:\Users\MyUser\Downloads\1341596825343s1jpg.jpg");
myPicBox.Dock = DockStyle.Fill;
this.MyTabPage.Controls.Add(myPicBox);

Where MyTabPage is the fourth page in a tab control. Any suggestions?

EDIT:

Stack Trace is Here

at ShipSiegeDashBoard.Form1.LoadSpaceStations() in C:\ShipSiegeTool\ShipSiegeDashBoard\Form1.cs:line 46 at ShipSiegeDashBoard.Form1..ctor() in C:\ShipSiegeTool\ShipSiegeDashBoard\Form1.cs:line 31 at ShipSiegeDashBoard.Program.Main() in C:\ShipSiegeTool\ShipSiegeDashBoard\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

Upvotes: 0

Views: 414

Answers (1)

comecme
comecme

Reputation: 6386

I suppose your MyTabPage control isn't initialized yet. You should not try to use until after it has been initialized.

Upvotes: 1

Related Questions