I am new to c#. I am trying to use Reflection to execute a method in a string variable.
This code will run without errors but only outpusts text to textBox1. What am I doing Wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
xx();
}
private void xx()
{
Type type = typeof(Form1);
System.Reflection.MethodInfo method = type.GetMethod("MyMethod");
Form1 c = new Form1();
string result = (string)method.Invoke(c, null);
textBox1.Text = result;
}
public string MyMethod()
{
textBox2.Text = "Hello Text Box 2";
return "Hello Text Box 1";
}
type here
>Solution :
You’re creating a new Form1 instance (called c). So you’re updating the c.textBox2.Text value, not the value of the current form.
In other words, method.Invoke(c, null) will call c.MyMethod().
You want to update the xx method to use the this keyword to invoke the method on the current form instance.
private void xx()
{
Type type = typeof(Form1);
System.Reflection.MethodInfo method = type.GetMethod("MyMethod");
string result = (string)method.Invoke(this, null);
textBox1.Text = result;
}