Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

.net - Binding a GridView to a Dynamic or ExpandoObject object

I'm using Rob Conery's Massive ORM, and I haven't been able to bind the resulting ExpandoObject to a GridView.

I did find another Stackoverflow question that suggests using a framework called impromptu, but I'm not sure if that would work for this. If you know it does, please provide a code sample to actually convert an ExpandoObject to something that the GridView control can bind to.

Worst case scenario, has anyone implemented an additional method (that can be shared) for Massive to convert the resulting ExpandoObject to a POCO?

any help is greatly appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...