Data Binding a Single Object when IEnumerable is Expected

Controls that can be used with data binding typically expect some kind of collection as the data source. One example is the ASP.NET DetailsView control. It displays a single record, but still expects a collection (to be exact: something that implements IEnumerable) to be assigned to its DataSource property.

I use a small extension method called WrapInEnumerable to help in this situation:

public static class ObjectExtensions
{
    public static IEnumerable<T> WrapInEnumerable<T>(this T t)
    {
        yield return t;
    }
}

With this function it is easy to use the DetailsView for displaying a single object:

myDetailsView.DataSource = myDataObject.WrapInEnumerable();

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.