Friday, May 11, 2012

How to convert a list into neat html table to display in UI.

I have look all over the internet to see if someone has written code that converts the enumerable list in C# and return you a html table so that you can directly display it on UI.  No luck. Here is what I have got I hope it helps someone. This code is test

Code Snippet
  1. public string GetAssociationValues()
  2.         {
  3.  
  4.             IEnumerable<string> results = _omniService.GetAllAssociations();
  5.  
  6.             // format a list into table of check boxes.
  7.  
  8.             var sbTable = new StringBuilder();
  9.             var sbRows = new StringBuilder();
  10.             var sbColumns = new StringBuilder();
  11.             int counter = 0;
  12.             foreach (string result in results)
  13.             {
  14.                 sbColumns.AppendFormat("<td><input type='checkbox' name='ImproveResultsAssociation' value='{0}' id='{0}'><span class='resAssociationText'>{0}</span></td>", result);
  15.                 counter++;
  16.  
  17.                 // change the 2 to what ever number of columns you want to display the text.
  18.                 if (counter % 2 == 0)
  19.                 {
  20.                     sbRows.Append("<tr>" + sbColumns.ToString() + "</tr>");
  21.                     sbColumns.Clear();
  22.                 }
  23.             }
  24.  
  25.             // last check if we are missing anything.
  26.             if (sbColumns.Length>0)
  27.             {
  28.                 sbRows.Append("<tr>" + sbColumns.ToString() + "</tr>");
  29.             }
  30.  
  31.             sbTable.Append("<table>" + sbRows.ToString() + "</table>");
  32.  
  33.             return sbTable.ToString();
  34.  
  35.  
  36.         }

No comments:

Post a Comment