开发者

NullReference Exception unhandled. C# Reflection

ControlType = "System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1";
System.Reflection.Assembly asm;
asm = typeof(Form).Assembly;
ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(ControlType);
ControlObject.Name = ControlName;

The next code gene开发者_如何学Crated following exception for me:

ControlObject.Name = ControlName;

NullReferenceException was unhandle Object reference not set to an instance of an object.


Assembly.CreateInstance is expecting a type name and you appear to be passing it the name of an instance of a type (namely, a PictureBox named PictureBox1.). Therefore, ControlObject is null and thus ControlObject.Name will throw a NullReferenceException.

It's not clear what you're trying to do, but that is why you are encountering the problem that you are. If you're trying to create a new instance of PictureBox I don't see why you don't just say new PictureBox(); this class has a public parameterless constructor. Alternatively, if you insist on reflection, you could say

controlType = PictureBox1.GetType();
controlObject = Activator.CreateInstance<Control>(controlType);

We could help more if we knew what you were trying to do instead of just throwing code that doesn't work at us and expecting us to solve world hunger.

Additionally,

ControlType = "System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1";
  1. Please rename this variable to controlType. You should use camel case for variable names.

  2. Why do you have your application class WindowsFormsApplication1 living in the system namespace System.Windows.Forms? Don't do this.


You're probably trying to write

ControlObject = new PictureBox();


Looks like CreateInstance returns null, which means the type wasn't found in the assembly. Is PictureBox1 a type or an object?


Surly your application is not in System.Windows.Forms namespace

"System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1"

Try:

ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(typeof(PictureBox));

or just

ControlObject = new PictureBox();

to create a new instance of control.

Or maybe you want to find an existing PictureBox control on your form?


It means that asm.CreateInstance(ControlType); is returning null.

So, ControlType has a wrong value. It is supposed to recieve as parameter a type http://msdn.microsoft.com/en-us/library/dex1ss7c.aspx and it seems that you are sending an instance PictureBox1.

It should be ControlType = "System.Windows.Forms.PictureBox";

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜