Reputation: 1712
I have employee class which contain more than 50 properties. I display all property name using PropertyInfo class on checkedboxlist on windows form. User can select more than one property to display in report. lets assume user selected name, title, phone, address then i need to get all in string and need to display it on report.
I can easily do this with if or switch but is there any other better way to do this instead of writing more than 50 switch statement?
Upvotes: 1
Views: 158
Reputation: 41569
You could loop through the selected properties and get their values via the PropertyInfo list you've already used;
//Say you have a Props instance defined as Generic.List(Of PropertyInfo)
//and an instance of your class named Inst
string[] selectedProps = {"Prop1","Prop2"};
string ret = "";
foreach (PropertyInfo pi in Props.Where(p => return selectedProps.Contains(p.Name))) {
ret &= ret & pi.GetValue(Inst,Nothing);
}
Disclaimer: This isn't tested, or even compiled, but should give a good idea of what's required.
Upvotes: 1
Reputation: 81680
You can use PropertyInfo
to get the value as well (if this is what you mean):
PropertyInfo propertyInfo = catalog.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
.Where(x => x.Name == propertyName).SingleOrDefault();
object propertyValue = propertyInfo.GetGetMethod().Invoke(customer);
Upvotes: 1
Reputation: 39329
When you generate the name of the property to display in the checkboxlist, also create an Expression that will retrieve the string representation of that property. Then for each checked item, run the expression on the current employee instance.
Upvotes: 1