Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't a method called with reflection have access to textBox?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading