mardi 17 novembre 2020

PropertyInfo.GetValue throws NullReferenceException

I want to create a Blazor DropDown component and I would use reflection in it. I give the data, the name of the text property and the name of the value property as parameters for it. Unfortunatelly when I get the value of the property it throws NullReferenceException after I get the value:

@foreach (TItem item in Data ?? Array.Empty<TItem>())
{
  PropertyInfo prop = typeof(TItem).GetProperty(ValueProperty);
  string text = prop.GetValue(item, null).ToString();
  ...
}

@code {
  [Parameter]
  public IEnumerable<TItem> Data { get; set; }
  [Parameter]
  public string ValueProperty { get; set; }
  [Parameter]
  public string TextProperty { get; set; }
}

TItem is:

public class DropDownData
{
  public int ValueInt { get; set; }
  public string ValueString { get; set; }
  public string Text { get; set; }
}

Thank you in advance.





Aucun commentaire:

Enregistrer un commentaire