jeudi 21 septembre 2023

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




Aucun commentaire:

Enregistrer un commentaire