jeudi 11 juin 2015

Dynamically set a property value

I have a table that has field names such as BC01, BC02, BC03 etc... rather then setting each property individually I am trying to use reflection to dynamically define the BC01, BC02 value. Below is the code I have thus far, the issue I'm having is that I get a null reference on the obj that I am passing, can't get my head around as to why!. Any help is greatly appreciated.

void Main() 
{
Production_Tracker_OSB_Work_Order workOrderInfo = (from r in Production_Tracker_OSB_Work_Orders where r.INTELL_SO_NBR.Equals("SAL994") select r).First();
var workOrderBarcodes = (from r in Production_Tracker_SFC_WIPs where r.WORK_ORDER.Equals(workOrderInfo.INTELL_SO_NBR) select r).ToArray();

int currentBarcodeIndex = 1;
for (int i = 0; i < workOrderBarcodes.Count(); i++)
    {
      var propertyName = "BC" + currentBarcodeIndex.ToString("D" + "2");

      workOrderInfo.SetPropertyValue(propertyName, workOrderBarcodes[i].BARCODE);
      currentBarcodeIndex ++;
    }

SubmitChanges();
}
public static class PropertyExtension
{
    public static void SetPropertyValue(this object obj, string propName, object value)
    {
      //obj.GetType().GetProperty(propName).SetValue(obj, value, null);
      Type type = obj.GetType();
      PropertyInfo prop = type.GetProperty(propName);
      prop.SetValue(obj, value, null);
    }

    public static object GetPropertyValue(this object obj, string propName)
    {
        return obj.GetType().GetProperty(propName).GetValue(obj, null);
    }
}

null-reference-exception





Aucun commentaire:

Enregistrer un commentaire