Binding a GridView to a Dynamic or ExpandoObject object

Since you can’t bind to an ExpandoObject, you can convert the data into a DataTable. This extension method will do that for you. I might submit this for inclusion to Massive.

/// <summary>
/// Extension method to convert dynamic data to a DataTable. Useful for databinding.
/// </summary>
/// <param name="items"></param>
/// <returns>A DataTable with the copied dynamic data.</returns>
public static DataTable ToDataTable(this IEnumerable<dynamic> items) {
    var data = items.ToArray();
    if (data.Count() == 0) return null;

    var dt = new DataTable();
    foreach(var key in ((IDictionary<string, object>)data[0]).Keys) {
        dt.Columns.Add(key);
    }
    foreach (var d in data) {
        dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
    }
    return dt;
}

Leave a Comment