Reputation: 23
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 generated following exception for me:
ControlObject.Name = ControlName;
NullReferenceException was unhandle Object reference not set to an instance of an object.
Upvotes: 0
Views: 417
Reputation: 241583
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";
Please rename this variable to controlType
. You should use camel case for variable names.
Why do you have your application class WindowsFormsApplication1
living in the system namespace System.Windows.Forms
? Don't do this.
Upvotes: 4
Reputation: 4030
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";
Upvotes: 0
Reputation: 46008
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?
Upvotes: 0
Reputation: 36852
Looks like CreateInstance returns null, which means the type wasn't found in the assembly. Is PictureBox1 a type or an object?
Upvotes: 0