How many times have you had to parse through a collection of objects, outputting nothing more than a comma-delimited list of items in the result set. Typically, you’ll do this:
<asp :repeater runat="server">
<itemtemplate>Eval("Name")</itemtemplate>
<separatortemplate>, </separatortemplate>
</asp>
If you were parsing a list of states, it might look like this:
Alabama, Alaska, Arizona, Arkansas
There’s an easier way to handle these simple needs: create a CollectionToString() method. This method would accept an IEnumerable and, using reflection, read a property and return a delimited string. Of course, you choose the property and delimiter.
Note that we have two versions of this method: one which accepts an IEnumerable, the other which accepts an object. This is done to avoid the necessary typecasting in your code, since Eval() returns everything as an object.
public static string CollectionToString(IEnumerable collection, string property, string delimiter)
{
IEnumerator enumerator = collection.GetEnumerator();
if (enumerator == null || enumerator.MoveNext() == false)
return String.Empty;
Type type = enumerator.Current.GetType();
PropertyInfo propInfo = type.GetProperty(property);
if (propInfo == null)
throw new Exception(String.Format("Property '{0}' not found in collection", property));
StringBuilder output = new . . .
→ Read More: A simple asp:Repeater replacement for simple needs
