Panel and Checkbox have been created and NullReferenceException wasthrown ...

  • Thread starter Thread starter Wolfgang Uhr
  • Start date Start date
W

Wolfgang Uhr

Hello

I've the following code

Panel pnlData = new System.Windows.Forms.Panel();
CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.AutoSize = true;
checkBox.Dock = System.Windows.Forms.DockStyle.Top;
checkBox.Name = "checkBox";
checkBox.TabIndex = 1;
checkBox.Text = "checkBox";
checkBox.UseVisualStyleBackColor = true;
try
{
pnlData.Container.Add(checkBox);
}
catch (NullReferenceException a)
{ }

And there the NullReferenceException will be thrown alwas.

Can me someone tell why?

Thanks for all

Best regars
Wolfgang Uhr
 
Hey there Wolfgang,

The problem is that container is null when you are trying to add. I'm
assuming you are wanting to make the checkbox appear in the panel, in which
case you actually just need to replace:

pnlData.Container.Add(checkBox);

with:

pnlData.Controls.Add(checkBox);

and that will place you checkbox onto the panel control. Hope that helps!
 
Hi Wolfgang,

Thanks for posting!

From the snippets of the current code, I have added the code into the Form
Load event in my own application. I can not reproduce the current issue
because all codes work fine. So I think maybe the null reference error is
related to the context for the current application. Could you please make a
simple demo and send it to me? This will help me to repro the current issue
and find some factors. My alias is (e-mail address removed) (remove
..online). Thanks for your understanding!

I'm looking forward your reply.

Regards,

Yuan Ren [MSFT]
Microsoft Online Support
 
Yuan said:
Could you please make a
simple demo and send it to me? This will help me to repro the current issue
and find some factors. My alias is (e-mail address removed) (remove
online). Thanks for your understanding!

I have just installed the very last Studio-Version 8.0.50727.42
(RTM.050727-4200) - German.

And realy: If I use pnlTreeData.Container.Add(checkBox), then the
command throws an error and if I use pnlTreeData.Controls.Add(checkBox),
the program works well.

I have used Container because this command will be used if i put a
Checkbox from the toolbox to the panel manually.

Ok, I'll use Container.

Best Regards
Wolfgang Uhr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top