June 11, 2014

Convert Object To DataTable in C#

Reflection using C #

Refraction is a "technique", you could say, to extract the metadata within an assembly nuestrasclases, for example, taking a class called Person, assuming that properties not only has this class name, utilizandoreflections can get a list of all properties that have this class and also get their valores.En the. NET Framework, reflection classes are encuentrandentro System.Reflection namespace.

Too many times we see the need to spend all the properties of an object to a DataTable, Here is an example:



/// <summary>
/// object to DataTable 
/// </summary>
private DataTable parseToDataTable(workspace.TheObject theObject)
{
 DataTable dat = new DataTable();
 
 workspace.TheObject datos = new dworkspace.TheObject();
     
 ///Agregamos las columnas con el tipo de datos correspondiente al Datatable
 foreach (PropertyInfo info in typeof(workspace.TheObject).GetProperties())
 {
   dat.Columns.Add(info.Name, info.PropertyType);
 }

 dat.AcceptChanges();

 DataRow row = dat.NewRow();
 
 //Cargamos los objetos que con los datos recibidos 

 datos = theObject;
 

 foreach (var property in datos.GetType().GetProperties())
 {
  
  row[property.Name] = property.GetValue(datos, null);
  
 }
 
 dat.Rows.Add(row);
 dat.AcceptChanges();
 return dat;
}


/// <summary>
/// object to DataTable 
/// </summary>
private DataTable parseToDataTable(workspace.TheObject.list theObject)
{
 DataTable deta = new DataTable();

 foreach (PropertyInfo info in typeof(workspace.TheObject.Item).GetProperties())
 {
  deta.Columns.Add(info.Name, info.PropertyType); 
 }
 deta.AcceptChanges();
 
 
 foreach (workspace.TheObject.Item item in theObject)
 {
  workspace.TheObject.Item datos = new workspace.TheObject.Item();
  datos = item;
  DataRow row = deta.NewRow();

  foreach (var property in datos.GetType().GetProperties())
  {
   row[property.Name] = property.GetValue(datos, null);
  }
  deta.Rows.Add(row);
 }
 
 deta.AcceptChanges();
 return deta;
}

See Also

Ditulis Oleh : Angelo Hari: 5:54 PM Kategori:

0 comentarios:

Post a Comment