开发者

Null Ref when adding TabPages at runtimes

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开发者_JAVA百科?

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(); 


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜