List<ExpandoObject>

Hiteshkumar Patel 21 Reputation points
2021-02-19T10:54:17.05+00:00

Hi Everyone, i am trying to get data from google sheet and update according i found sum example code over internet in this code i can read all data from Google Sheet but in this code they use List<ExpandoObject> object where all data is stored i don't know about anything how to get that data in my datagridview i am completely blind about List<ExpandoObject> can any one help about this

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,976 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 117.6K Reputation points
    2021-02-19T14:45:09.09+00:00

    To display a List<ExpandoObject>, creating columns automatically based on data, add a DataGridView to your form, do not set any property yet, and execute the next code:

    // Sample list
    List<ExpandoObject> list = new List<ExpandoObject>( );
    
    dynamic obj0 = new ExpandoObject( );
    obj0.Name = "John";
    obj0.Age = 120;
    list.Add( obj0 );
    
    dynamic obj1 = new ExpandoObject( );
    obj1.Name = "Sarah";
    obj1.Age = 117;
    list.Add( obj1 );
    
    
    dataGridView1.AutoGenerateColumns = true;
    
    var dt = new DataTable( );
    ExpandoObject first = list.First( );
    var first_d = (IDictionary<string, object>)first;
    
    foreach( var key in first_d.Keys )
    {
       var val = list.Select( o => ( (IDictionary<string, object>)o )[key] ).FirstOrDefault( v => v != null );
       dt.Columns.Add( key, val?.GetType( ) ?? typeof( object ) );
    }
    
    foreach( var obj in list )
    {
       dt.Rows.Add( dt.Columns.Cast<DataColumn>( ).Select( c => ( (IDictionary<string, object>)obj )[c.ColumnName] ).ToArray( ) );
    }
    
    dataGridView1.DataSource = dt;
    

    The example uses a list with some sample data. If it works, then try your real list.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.