jeudi 20 juillet 2017

Create Dynamic properties from Datatable

I have below class with one property.

  public class MfrYearEqpType
  {   
    public string EqpType { get; set; }

    public MfrYearEqpType()
    {
    }
  }

I wanted to create dynamic properties(Datatable column names) to my class "MfrYearEqpType" and set the values from below Datatable.

DataTable dt = getData();

This table contains 26 rows and 10 columns of data.

I have gone through the below link. But I am not sure how to handle my case.

Dynamically adding properties to an Object from an existing static object in C#

And also I have used ExpandoObject. I have done below sample.

  DataTable dt = getData();

  List<dynamic> expandoList = new List<dynamic>();

  foreach (DataRow row in dt.Rows)
  {
    //create a new ExpandoObject() at each row
   var expandoDict = new ExpandoObject() as IDictionary<String, Object>;
   foreach (DataColumn col in dt.Columns)
   {
      //put every column of this row into the new dictionary
      expandoDict.Add(col.ToString(), row[col.ColumnName].ToString());
   }

   //add this "row" to the list
   expandoList.Add(expandoDict);
   }

But my aim is to create the List of MfrYearEqpType. So that I can bind List of MfrYearEqpType to Gridview.

Please help me on this.





Aucun commentaire:

Enregistrer un commentaire