SetValue using reflection

S

samlee

Hi, all
I must apologise if these questions had been asked before.

1)
Why Assembly.Load("System.Windows.Forms") ?

2)
How can I set/get property of an object using reflection.
More specfically, how to acomplish the effect of
this.Text = "Hello World";
in the following program

Thank in advance,
================================================
using System;
using System.Reflection;
using System.IO;

public class Form1
{
static object sf;
public Form1()
{
//this.Text = "Hello World";
Assembly a1 =
Assembly.LoadFrom(@"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Windows.Forms.dll");
Type t = a1.GetType("System.Windows.Forms.Form");
sf= Activator.CreateInstance (t);
// Type t1 = a1.GetType("System.Windows.Forms.Control");
// PropertyInfo prop= t1.GetProperty("Text", new
Type[]{typeof(string)}); // kein Parameter
// object[] args = new object[]{"hello world" };
// object result = prop.SetValue(t, args,null); // kein Parameter
}

static void Main()
{
//System.Windows.Forms.Application.Run(new Form1());
Form1 s= new Form1();
Assembly a1 =
Assembly.LoadFrom(@"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Windows.Forms.dll");
// Assembly a1 = Assembly.Load("System.Windows.Forms");
Type t1 = a1.GetType("System.Windows.Forms.Form");
Type t2 = a1.GetType("System.Windows.Forms.Application");
MethodInfo method = t2.GetMethod("Run", new Type[]{t1});
object result = method.Invoke(null, new object[]{sf});
}
}
 
M

Mattias Sjögren

1)
Why Assembly.Load("System.Windows.Forms") ?

Why it fails? You should specify the full assembly name

"System.Windows.Forms, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"

2)
How can I set/get property of an object using reflection.
More specfically, how to acomplish the effect of
this.Text = "Hello World";
in the following program

t1.GetProperty("Text", typeof(string)).SetValue(sf, "Hello World",
null);



Mattias
 
S

samlee

t1.GetProperty("Text", typeof(string)).SetValue(sf, "Hello World",

Thank you very much, It works.

A related question. How to define type Form1 as a derived type from
System.Windows.Forms.Form and its overload methods and ctor?
Because I wish to implement the following using reflection.

public class Form1:System.Windows.Forms.Form
{
public Form1() {this.Text = "Hello World";}
}
 

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

Top