GetProperty
returns a
PropertyInfo
; you need to call the
GetValue
method on that
PropertyInfo
, passing in the instance of the class, to get the actual value of the property.
But there's a much simpler solution: have your entity classes implement an interface, or inherit from a base class. Then add a type constraint to your generic type parameter, and get rid of all of the reflection.
public interface IDropDownListProvider
{
IEnumerable DataFromService { get; }
string DropDownListDataTextField { get; }
Exception LastException { set; }
}
public class DropDownListFiller<T> where T : IDropDownListProvider
{
public T SelectedEntity { get; set; }
public virtual DropDownList LoadDropDownList(DropDownList ddl, bool AddChooseItem = true, string selectedValue = null, string OtherDataTextField = null)
{
try
{
ddl.DataSource = SelectedEntity.DataFromService;
ddl.DataTextField = OtherDataTextField ?? SelectedEntity.DropDownListDataTextField;
ddl.DataValueField = "Id";
ddl.DataBind();
if (AddChooseItem)
{
if (ddl.Items.Count == 0)
{
ddl.Items.Insert(0, new ListItem("Geen vrije keuze mogelijk", "0"));
}
else
{
ddl.Items.Insert(0, new ListItem("Selecteer a.u.b.", "0"));
}
}
if (!string.IsNullOrWhiteSpace(selectedValue))
{
MarinEntities.Logging.Log.AddMessage($"selectedValue: {selectedValue}");
var selectedItem = ddl.Items.FindByValue(selectedValue) ?? ddl.Items.FindByText(selectedValue);
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
}
MarinEntities.Logging.Log.AddMessage($"ddl.SelectedValue: {ddl.SelectedValue}");
}
}
catch (Exception err)
{
SelectedEntity.LastException = err;
MarinEntities.Logging.Log.AddException(err);
}
return ddl;
}
}