I have a collection of IEnumerable that is being passed to an extension
method that populates a DropDownList. I would also like to pa
Based off Jon's answer and this post, it gave me an idea. I passed the DataValueField and DataTextField as Expression to my extension method. I created a method that accepts that expression and returns the MemberInfo for that property. Then all I have to call is .Name and I've got my string.
Oh, and I changed the extension method name to populate, it was ugly.
public static void populate(
this DropDownList source,
IEnumerable dataSource,
Expression> dataValueField,
Expression> dataTextField) {
source.DataValueField = getMemberInfo(dataValueField).Name;
source.DataTextField = getMemberInfo(dataTextField).Name;
source.DataSource = dataSource;
source.DataBind();
}
private static MemberInfo getMemberInfo(Expression> expression) {
var member = expression.Body as MemberExpression;
if(member != null) {
return member.Member;
}
throw new ArgumentException("Member does not exist.");
}
Called like so...
myDropDownList.populate(states,
school => school.stateCode,
school => school.stateName);