Welcome to Dream.In.Code
Become a C# Expert!

Join 149,478 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,583 people online right now. Registration is fast and FREE... Join Now!




Casting objects from a string variable

 
Reply to this topicStart new topic

Casting objects from a string variable, c# puzzler

weedweaver
1 May, 2007 - 02:34 PM
Post #1

New D.I.C Head
*

Joined: 1 May, 2007
Posts: 26


My Contributions
hey guys,
Was wondering if anyone could help me out, say i am reading an XML file, or I have a string variable with the word "Panel" or "TextBox" or "label" etc.. how can i create an instance of that kind of object using the value of the variable

e.g. I read a an XML file and find the word "Panel" as a string, how can i dynamically crate a .NET Panel at runtime (or whatever kind of object depending on the value of the string)

Cheers guys.
User is offlineProfile CardPM
+Quote Post

weedweaver
RE: Casting Objects From A String Variable
2 May, 2007 - 12:45 AM
Post #2

New D.I.C Head
*

Joined: 1 May, 2007
Posts: 26


My Contributions
p.s. what i *DONT* want to do is add a case statement (or an if statement) like:

string _controlToLoad = /*Value read from file*\
switch(_controlToLoad)
{
case "Panel" :
{
Panel p = new Panel();
break;
}
}

I dont want to do that cos I have to rebuild then if I wanted to add a new control which wasnt previously in the case statment.
User is offlineProfile CardPM
+Quote Post

JellyBean
RE: Casting Objects From A String Variable
2 May, 2007 - 01:10 AM
Post #3

D.I.C Head
**

Joined: 25 Apr, 2007
Posts: 60


My Contributions
Take a look at the Activator.CreateInstance method in the System.Reflection library.

I think this is a good place for you to start....

User is offlineProfile CardPM
+Quote Post

weedweaver
RE: Casting Objects From A String Variable
2 May, 2007 - 02:54 AM
Post #4

New D.I.C Head
*

Joined: 1 May, 2007
Posts: 26


My Contributions
Ok, I have found a couple of solutions neither of which im entiirely happy with:

Solution 1:

CODE

        public Control LoadControl(string typeName)
        {
            return LoadControl(Type.GetType(typeName));
        }

        public Control LoadControl(Type controlType)
        {
            if (controlType != null)
            {
                return Activator.CreateInstance(controlType) as Control;
            }
            return null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Control test = LoadControl("System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            if (test != null)
            {
                this.Controls.Add(test);
            }
        }


The problem with the above is that I have to specify the fully qualified asembly name which i dont want to do for compatibility reasons (.NET 1 and 3 will have different public key tokens etc.)

Solution 2:

CODE

            string strType = "System.Windows.Forms.TextBox";
            Assembly asm = Assembly.LoadWithPartialName("System.Windows.Forms");
            Type tp = asm.GetType(strType);
            object obj = Activator.CreateInstance(tp);


Unfortunatly LoadWithPartialName is now obsolete in framework 2 (although you can still use it), it has been replaced with Assembly.Load()

Now unfortunatly Assembly.Load("System.Windows.Forms"), doesnt work.
I need to find a way of creating the System.Windows.Forms assembly without having to use the LoadFrom method with the Path as the parameter e.g.

Assembly.LoadFrom(@"C:\WINDOWS\Microsoft.NET\Framework\*version*\System.Windows.Forms.dll");

Any ideas???
User is offlineProfile CardPM
+Quote Post

weedweaver
RE: Casting Objects From A String Variable
2 May, 2007 - 03:49 AM
Post #5

New D.I.C Head
*

Joined: 1 May, 2007
Posts: 26


My Contributions
Found a solution which is slightly better :-)

CODE

string strType = "System.Windows.Forms.TextBox";
Assembly asm = typeof(Form).Assembly;
Type tp = asm.GetType(strType);
object obj = Activator.CreateInstance(tp);

User is offlineProfile CardPM
+Quote Post

JellyBean
RE: Casting Objects From A String Variable
2 May, 2007 - 04:01 AM
Post #6

D.I.C Head
**

Joined: 25 Apr, 2007
Posts: 60


My Contributions
QUOTE(weedweaver @ 2 May, 2007 - 04:49 AM) *

Found a solution which is slightly better :-)

CODE

string strType = "System.Windows.Forms.TextBox";
Assembly asm = typeof(Form).Assembly;
Type tp = asm.GetType(strType);
object obj = Activator.CreateInstance(tp);


Nice! smile.gif I was looking for something similar last week. I also found that Assembly.Load didn't work the way I expected or wanted.

Thanks for posting your solution. icon_up.gif

User is offlineProfile CardPM
+Quote Post

weedweaver
RE: Casting Objects From A String Variable
2 May, 2007 - 04:34 AM
Post #7

New D.I.C Head
*

Joined: 1 May, 2007
Posts: 26


My Contributions
Here is a slightly fuller solution ;

CODE

string strType = "System.Windows.Forms.TextBox";
Assembly asm = typeof(Form).Assembly;
Type tp = asm.GetType(strType);
object obj = Activator.CreateInstance(tp);
if (obj is Control)
            {
                Control test = (Control)obj;
                test.Text = "Test";
                this.Controls.Add(test);
            }

User is offlineProfile CardPM
+Quote Post

adWebDev
RE: Casting Objects From A String Variable
31 Mar, 2008 - 03:09 AM
Post #8

New D.I.C Head
*

Joined: 31 Mar, 2008
Posts: 1

QUOTE(weedweaver @ 2 May, 2007 - 05:34 AM) *

Here is a slightly fuller solution ;

CODE

string strType = "System.Windows.Forms.TextBox";
Assembly asm = typeof(Form).Assembly;
Type tp = asm.GetType(strType);
object obj = Activator.CreateInstance(tp);
if (obj is Control)
            {
                Control test = (Control)obj;
                test.Text = "Test";
                this.Controls.Add(test);
            }




How do you get to the methods / properties of the objects you create?

I came across your code above and amended it for WebControls. I can hance output a textbox to the browser. However, I am stuck when it comes to obtaining the value of the text property of this textbox, eg. myTestVar = test.text.

I'm obviously looking at this the wrong way - could you give me some pointers guys

Thanks in advance,
Adam

This post has been edited by adWebDev: 31 Mar, 2008 - 04:51 AM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 03:48PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month