0

I need to instantiate various objects and add them to form. The objects classes (and some other information, such as coordinates and text) are stored in a table, as strings.

All I managed to do so far is this:

var obj = Activator.CreateInstance(typeof(Form).Assembly.GetType("System.Windows.Forms.TextBox"));

How do I access a property of the above object? I don't want to cast it to a TextBox because it defeats the initial purpose - to be able to instantiate the object directly from the string. It may be a textbox, or a combobox, or anything else, can't use a switch.

Thank you :)

JoelC
  • 3,664
  • 9
  • 33
  • 38
Grigore Dolghin
  • 121
  • 2
  • 11
  • The `Type` Object has an array of `PropertyInfo` These are all the properties of the object. It also includes methods to get and set values for that property on a specific object. – pquest Sep 15 '14 at 13:38
  • You can parse the type of the object from string and then instantiate – Dark Knight Sep 15 '14 at 13:39
  • You could also declar obj as dynamic `dynamic obj = Activator.CreateInstance(typeof(Form).Assembly.GetType("System.Windows.Forms.TextBox"));` – Ben Robinson Sep 15 '14 at 13:44
  • I have no idea why this question got marked as duplicate, because the linked question (above) isn't the same as this question, but okay. Anyway, here's the code that I would provide to you for assigning properties and placing the control on your form: http://pastebin.com/Cw2VPHaF – Jevgeni Geurtsen Sep 15 '14 at 13:57
  • Thank you guys and sorry for the duplicate question. The dynamic object suits me best. – Grigore Dolghin Sep 15 '14 at 13:58
  • @TheDutchMan: The duplicate question is the general solution. Not specific to TextBoxes. Feel free to tell me what I missed and I will be happy to reopen. – Patrick Hofman Sep 15 '14 at 14:06
  • I understand why this got marked as duplicate, as the property setting part through reflection is the problem here. But the main question was how to add controls which are saved in a table to the form without using the most upper type. But I guess its alright as he already commented here he solved it. – Jevgeni Geurtsen Sep 15 '14 at 14:15
  • @TheDutchMan: It seemed to me the question title was off from the actual question in the body. That question is answered. Adding a control to a form wasn't the issue IMHO. – Patrick Hofman Sep 15 '14 at 14:49

0 Answers0