Question

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.

Was it helpful?

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());

OTHER TIPS

The properties .Text and .Name are not static. So, you can't get the value of that property without calling a Constructor of that form. You must create an object of that form to read the property.

List<String> formList = new List<String>();
Assembly myAssembly = Assembly.GetExecutingAssembly();

foreach (Type t in myAssembly.GetTypes())
{
    if (t.BaseType == typeof(Form))
    {
        ConstructorInfo ctor = t.GetConstructor(Type.EmptyTypes);
        if (ctor != null)
        {
            Form f = (Form)ctor.Invoke(new object[] { });
            formList.Add("Text: " +  f.Text + ";Name: " + f.Name);
        }
    }
}

To read properties, you need to make new instance of the form. Above you're browsing all the types that are inheriting from the Form-class. You can read the different Form-class names, but that's it.

To read the Text-property, you need to browse instances of your Forms. You can use Application.OpenForms to read the Text and Name properties of your open forms.

You can try this to read the properties:

List<KeyValuePair<string, string>> formDetails = new List<KeyValuePair<string, string>>();
Type formType = typeof(Form);
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
   if (formType.IsAssignableFrom(type))
   {
      using (var frm = (Form)Activator.CreateInstance(type))
      {
         formDetails.Add(new KeyValuePair<string, string>(frm.Name, frm.Text));
      }
   }
}

I fixed the code and it should work now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top