Access bools of a model class through reflection and access their values

0

I have a model class:

using System;
using System.Collections.Generic;

namespace UserManagement.Models
{
    public partial class ComBox
    {
        public int FkSystem { get; set; }
        public int FkUsers { get; set; }
        public bool? Pkw { get; set; }
        public bool? Trpv { get; set; }
        public bool? Trcv { get; set; }
        public bool? Lkw { get; set; }
        public bool? Smart { get; set; }
        public bool? Itresponsible { get; set; }
        public bool? DealerPrincipalSales { get; set; }
        public bool? SalesManager { get; set; }
        public bool? SalesAdministrator { get; set; }
         .
         .
         .    
        public virtual Systems FkSystemNavigation { get; set; }
        public virtual Users FkUsersNavigation { get; set; }
    }
}

Now I have to tick a checkbox for every bool in a PDF document which I generate. My problem is: not only do I have one model class but 30. And I'd like to automatically iterate over each model, extract the booleans and tick a checkbox, depending on the value of the bool.

ComBox cfgItem = (ComBox)cfgList[cl.FkID];

IEnumerable<PropertyInfo> Cfg = cfgItem.GetType()
   .GetProperties()
   .Where(p => p.PropertyType == typeof(bool?));

foreach (PropertyInfo b in Cfg) 
{
   if ( (Nullable<bool>)b.GetValue(b, null) == true)                                  
      form.GetField(cl.Systemname+"_"+b.Name).SetValue("Yes");
}

For the if-line, the system gives me the following error:

System.Reflection.TargetException HResult=0x80131603
Message=Object does not match target type.

Any ideas how I can address this error?

c#
asp.net-core
razor
blazor-server-side
asked on Stack Overflow Jan 16, 2020 by d00d

1 Answer

1

This bit is wrong:

b.GetValue(b, null)

b is a PropertyInfo. The parameter you pass to GetValue needs to be the object instance to get the value from, in your case cfgItem. You don't need to pass a second parameter:

b.GetValue(cfgItem);
answered on Stack Overflow Jan 16, 2020 by canton7

User contributions licensed under CC BY-SA 3.0