public static string ToHtmlTable(this IEnumerable list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle) { var result = new StringBuilder(); if (String.IsNullOrEmpty(tableSyle)) { result.Append("<table id=\"" + typeof(T).Name + "Table\" >"); } else { result.Append("<table id=\"" + typeof(T).Name + "Table\" class=\"" + tableSyle + "\" >"); } var propertyArray = typeof(T).GetProperties(); foreach (var prop in propertyArray) { if (String.IsNullOrEmpty(headerStyle)) { result.AppendFormat("<th >{0}</th >", prop.Name); } else { result.AppendFormat("<th class=\"{0}\" >{1}</th >", headerStyle, prop.Name); } } for (int i = 0; i < list.Count(); i++) { if (!String.IsNullOrEmpty(rowStyle) && !String.IsNullOrEmpty(alternateRowStyle)) { result.AppendFormat("<tr class=\"{0}\" >", i % 2 == 0 ? rowStyle : alternateRowStyle); } else { result.AppendFormat("<tr >"); } foreach (var prop in propertyArray) { object value = prop.GetValue(list.ElementAt(i), null); result.AppendFormat("<td >{0}</td >", value ?? String.Empty); } result.AppendLine("</tr >"); } result.Append("</table >"); return result.ToString(); }
Monday, January 30, 2012
Best Extension Methods: From IEnumerable To HTML Table
This extension method is to convert IEnumerable to HTML Table String. You can use it when you wants to show values of IEnumerable on Screen in form of HTML Table.
Share This!
Labels:
C#.NET,
Extension Methods
Subscribe to:
Post Comments (Atom)
1 comment:
It doesn't work with simple List!
Post a Comment