Naren
Naren

Reputation: 65

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.

Upvotes: 0

Views: 2056

Answers (1)

Tanveer Badar
Tanveer Badar

Reputation: 5512

Assuming you are talking about ASP.NET here, you can directly bind your data table to a GridView's DataSource property.

If you are happy with these 10 columns displaying as default, you can set AutoGenerateColumns property to true. Otherwise, you may want to define <asp:BoundField /> or <asp:TemplateField /> columns as appropriate. Bound fields will let you at least format the value for a particular column while template fields will allow full customization where you can provide an defining how to render a particular field.

Upvotes: 0

Related Questions