tags:

views:

15

answers:

2

This is a sample code I wrote to add some tab pages with the controls in them at run time. but when I run it , I get a Null Ref exception error. what part I am doing wrong?

TabPage[] tabPages = new TabPage[2];
CheckBox ck = new CheckBox();
tabPages[0].BackColor = Color.Firebrick;
tabPages[0].Controls.Add(ck);
tabPages[1].BackColor = Color.Firebrick;
tabPages[1].Controls.Add(ck);
tabGuy.SuspendLayout();
tabGuy.TabPages.Add(tabPages[0]);
tabGuy.TabPages.Add(tabPages[1]);
tabGuy.ResumeLayout(); 
+4  A: 

You're missing tabPages[0] = new TabPage() and tabPages[1] = new TabPage() before any assignment. Creating an array assigns every of its elements to its default value, that is null for any reference type.

Julien Lebosquain
+3  A: 

It looks to me that you are only creating a new array of TabPage's, I would suggest trying

tabPages[0] = new TabPage();

If this is a compiled application, you can run this in the debugger, you should be able to see exactly what line is throwing the exception. In this case I would expect it to be at the line:

tabPages[0].BackColor = Color.FireBrick;
TaRDy
two answers which are basically the same, submitted at the same time, but you have fewer points, so I'm giving you the up-vote :)
ckramer