mercredi 19 juillet 2017

Create ExpandoObject using Datatable

I am new to C# and gone through lot of questions in Stackoverflow.com and didn't find the solution for my requirement. So finally posting here.

My requirement is to create the dynamic properties from datatable column names and set the values to dynamic properties from datatable. and finally bind the data to gridview.

So I decided to follow below steps to achieve this functionality( kindly Correct me If I am wrong)

my datatable contains 26 rows and 10 columns of data

  1. Create a Class A
  2. Add dynamic properties to A from datatable(column names)
  3. Set values to properties of A
  4. Make class A to List of A
  5. Bind List of A to GridView

I have done the below steps

1.

[Serializable]
public class A
{   
  public A() 
  {   
  }  
}

2 & 3.

DataTable dt = getData();

dynamic expando = new ExpandoObject();

foreach (DataRow row in dt.Rows)
{
   foreach (DataColumn col in dt.Columns)
   {
     var expandoDict = expando as IDictionary<String, Object>;

     if (expandoDict.ContainsKey(col.ToString()))
       expandoDict[col.ToString()] = row[col.ColumnName].ToString();
     else
       expandoDict.Add(col.ToString(), row[col.ColumnName].ToString());
   }
}

After executing the above for loop, "expando" object contains only last row of datatable.

Can you please help me how to fix the steps 2 to 5.





Aucun commentaire:

Enregistrer un commentaire