Reputation: 83
I want to pass variables from one form to another.
This is a constructor in form2:
public Form2 (int getId,string getText)
In form1 I'm trying to pass variables like this
var obj = (Form)Activator.CreateInstance(Type.GetType("myproject.Form2"),1,"test");
obj.ShowDialog();
I'm getting error:
Additional information: Constructor on type 'myproject.Form2' not found.
How can I pass a variable?
Upvotes: 3
Views: 7199
Reputation: 12171
You should cast to Form2
, not to Form
.
I don't know where is problem (if you cast to correct type), but if you have corresponding constructor, your code works fine for me.
You can try to pass arguments as object[]
(object
array) - CreateInstance(Type type, object[] args), but also you can pass arguments by the way you pass them (because method accepts params object[] args
).
Try to replace this line:
var obj = (Form)Activator.CreateInstance(Type.GetType("myproject.Form2"),1,"test");
by this:
var obj =
(Form2)Activator.CreateInstance(Type.GetType("myproject.Form2"), new object[] {1, "test"});
Also, you can use typeof
to get Type
instance:
var obj = (Form2)Activator.CreateInstance(typeof(Form2), new object[] {1, "test"});
But if you know which type of instance to create at compile time, you should simply create your object using new
:
var obj = new Form2(1, "test");
Upvotes: 3
Reputation: 169270
Why don't you just create an instance of the Form without using reflection?
Form2 frm2 = new Form2(1, "test");
frm2.ShowDialog();
If you want to use reflection for some reason your code should work provided that the Form2
class is defined within the "myproject" namespace in the same assembly.
namespace myproject
{
public class Form2 : Form
{
public Form2 (int getId, string getText)
{
InitializeComponent();
}
}
}
If it is defined in another assembly you should read this:
Resolve Type from Class Name in a Different Assembly
Upvotes: 2
Reputation: 2309
As far as my understanding reaches you are misusing the Activator class. What you really should be using is the 'new' keyword to create the object as you are well aware of the type that you will be creating.
Here's how it should look :
var obj = new Form2(1,"test");
Using the Activator class only makes sense when you aren't aware what the type that you will create really is.
Upvotes: 2