mercredi 14 octobre 2015

C# reflection control properties parameter count mismatch exception

I have a textbox and a datagridview with a custom property that's bool. I'm using reflection to enable the textbox or datagridview at runtime depending how my custom property is set. The code loops through each controls properties and if it's my custom property and true then I enable the control.

I'm getting a "Parameter count mismatch" exception on the datagridview only. I have found a work around but I'm not sure why it works. The first foreach loop below throws an exception. The second does not.

I've done some searching and what I found points to the property being an indexer. I know it's not and GetIndexParameters().Length for the property is 0 with both control types. Why doesn't the first example work?

    Type type = control.GetType();
    PropertyInfo[] properties = type.GetProperties();

    //Exception
    foreach (PropertyInfo property in properties)
    {
        if (property.Name == PropName & Convert.ToBoolean(property.GetValue(control, null)) == true)
            (control as Control).Enabled = true;
    }

    //No excpetion
    foreach (PropertyInfo property in properties)
    {
        if (property.Name == PropName)
            if(Convert.ToBoolean(property.GetValue(control, null)) == true)
                (control as Control).Enabled = true;
    }





Aucun commentaire:

Enregistrer un commentaire