Search code examples
c#winformsreflectionsetvalue

How to Set Value for Field in winforms c# using Reflection


My Project have this:

private clsDTO_Error DTO_Error; --> Have PropertyName = ID
private clsDTO_Right DTO_Right;
FieldInfo f = this.GetType().GetField(DTO_Error, BindingFlags.NonPublic | BindingFlags.Instance);

This example is working properly

DTO_Right.GetType().GetProperty(PropertyName).SetValue(DTO_Right, "OK", null);

or

f.FieldType.GetProperty("ID").SetValue(DTO_Error,"OK",null);

I have a problem in this:

f.FieldType.GetProperty("ID").SetValue(f.FieldType,"ERROR",null);

Any ideas for this?

Thanks!


Solution

  • I have my answer that I use Directionary

    private Dictionary<string, object> myDictionary = new Dictionary<string, object>();
    //Add this in Form Load
    myDictionary.Add("DTO_Error", DTO_Error);
    //Set Value
    PropertyInField.SetValue(myDictionary[DTO_Error], "OK", null);