Recently I had someone posting a question about how to access the Text properties of a different control. I thought of using reflection, because you don’t need to know the type of control you are handling and you don’t need to type cast the object.

If you are handling one specific control, there is no point using reflection, I would suggest just type cast it.

Below is a code snippet from an example I have written to demonstrate how to share one event method with multiple controls on a form. In the method it will get the string value from the Text property of the selected control.

Source Code: ReflectionExample1.zip

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;
using System.Reflection;

namespace ReflectionExample1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void DisplayText(object sender, MouseEventArgs e)
        {
            Type type = sender.GetType();
            PropertyInfo pInfo = type.GetProperty("Text");
            String value = pInfo.GetValue(sender, null).ToString();
            MessageBox.Show(value);
        }
    }
}
Shares