Based on John's answer and this one , it gave me an idea. I passed DataValueField and DataTextField as Expression<Func<TObject, TProperty>> to my extension method. I created a method that takes this expression and returns MemberInfo for this property. Then all I need to call is .Name , and I have my string .
Oh, and I changed the name of the extension method to populate , it was ugly.
public static void populate<TObject, TProperty>( this DropDownList source, IEnumerable<TObject> dataSource, Expression<Func<TObject, TProperty>> dataValueField, Expression<Func<TObject, TProperty>> dataTextField) { source.DataValueField = getMemberInfo(dataValueField).Name; source.DataTextField = getMemberInfo(dataTextField).Name; source.DataSource = dataSource; source.DataBind(); } private static MemberInfo getMemberInfo<TObject, TProperty>(Expression<Func<TObject, TProperty>> expression) { var member = expression.Body as MemberExpression; if(member != null) { return member.Member; } throw new ArgumentException("Member does not exist."); }
Called like that ...
myDropDownList.populate(states, school => school.stateCode, school => school.stateName);
source share