Search code examples
c#winformstexttypesgetproperty

How to get the Text property of each form


I have been searching for almost a week now, but I can't seem to solve my simple problem. I want to get all the name and text properties of all the forms in my project.

Here is my code:

using System.Reflection;

Type Myforms = typeof(Form);
foreach (Type formtype in Assembly.GetExecutingAssembly().GetTypes())
{
    if (Myforms.IsAssignableFrom(formtype))
    {
      MessageBox.Show(formtype.Name.ToString()); // shows all name of form
      MessageBox.Show(formtype.GetProperty("Text").GetValue(type,null).ToString()); // it shows null exception
    }
}

I need the name and the .Text of the form to store it in the database to control user privileges.


Solution

  • MessageBox.Show(formtype.GetProperty("Text").GetValue(type,null).ToString()); shows exception because you need an instance of Form to get its Text property as Form does not static Text property.

    To get the default Text property create a instance

    var frm = (Form)Activator.CreateInstance(formtype);
    MessageBox.Show(formtype.GetProperty("Text").GetValue(frm, null).ToString());