Posted By

jermeyz on 09/15/10


Tagged

dropdown c Generic


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Generic List bind to a drop down


 / Published in: C#
 

  1. /// <summary>
  2. /// Converts an IEnumberable to a list of SelectListItems
  3. /// </summary>
  4. /// <typeparam name="T">Type of items in data</typeparam>
  5.  
  6. /// <typeparam name="TValueType">Type of property to be used for the Value property</typeparam>
  7. /// <typeparam name="TTextType">Type of property to be used for the Textproperty</typeparam>
  8. /// <param name="data">List to convert</param>
  9. /// <param name="defaultItem">An optional extra listItem appeneded at the beginning of the list</param>
  10. /// <param name="valueProperty">property of T to be used for the Value property</param>
  11. /// <param name="textProperty">property of T to be used for the Text property</param>
  12. /// <param name="selectedValue">Item in return value that should be selected</param>
  13. /// <returns></returns>
  14. public static List<SelectListItem> ToSelectList<T, TValueType, TTextType>(IEnumerable<T> data, SelectListItem defaultItem, Expression<Func<T, TValueType>> valueProperty, Expression<Func<T, TTextType>> textProperty, string selectedValue)
  15. {
  16. var list = new List<SelectListItem>();
  17.  
  18. if (defaultItem != null)
  19. {
  20. list.Add(defaultItem);
  21. }
  22. if (data == null)
  23. return list;
  24.  
  25. var memberInfo = textProperty.Body as MemberExpression;
  26. var textPropName = memberInfo.Member.Name;
  27.  
  28. var valmemberInfo = valueProperty.Body as MemberExpression;
  29. var valuePropName = valmemberInfo.Member.Name;
  30.  
  31.  
  32. Type t = typeof(T);
  33.  
  34. var textProp = t.GetProperties().Where(prop => prop.Name == textPropName).Single();
  35. var valueProp = t.GetProperties().Where(prop => prop.Name == valuePropName).Single();
  36.  
  37. foreach (var item in data)
  38. {
  39.  
  40. var text = textProp.GetValue(item, null);
  41. var value = valueProp.GetValue(item, null);
  42.  
  43. list.Add(new SelectListItem()
  44. {
  45. Text = text.ToString(),
  46. Value = value.ToString(),
  47. Selected = (selectedValue == value.ToString())
  48. }
  49. );
  50. }
  51.  
  52. return list;
  53. }

Report this snippet  

You need to login to post a comment.