2009-07-20 3 views
0

J'essaie de convertir automatiquement les propriétés de l'objet en DataTable (object est array et possède des propriétés qui sont instanciées à partir de la classe spéciale qui a un type de valeur).Puis-je stocker des données de tableau sérialisables dans DataColumn?

Le code:

static public DataTable f_GetDataTableFromClassObject(object _objInstance) 
{ 
    // geri dönecek datatable 
    DataTable dataTable = new DataTable(); 

    // nesnenin propertyleri içinde dolanalım ve datatable içine kolon olarak ekleyelim. 
    foreach (var p in f_GetProperties(_objInstance)) 
    { 
     if (p.PropertyType.IsArray) 
     { 
      if (p.PropertyType.BaseType.Attributes.ToString().IndexOf("Serializable")>-1) 
      { 
       // Now i want to store to DataColumn this properties which is instantiated DifferentClass[] and Serializable     
      } 
     } 
     else 
     { 
      dataTable.Columns.Add(new DataColumn(p.Name, p.PropertyType));      
     } 
    } 

    // ve tablomuz. 
    return dataTable; 
} 

Que dois-je faire pour stocker ce tableau dans DataColumn?

+1

Essayez d'utiliser le type System.Object. –

Répondre

0
class Program 
{ 
    static void Main(string[] args) 
    { 
     Person cenk = new Person() { adi = "Cenk", yasi = 18 }; 

     List<Person> lst = new List<Person>() 
           { 
            cenk, 
            new Person() {adi = "Cem", yasi = 17, harfler = new[] {"a","b","c"}}, 
            new Person() {adi = "Canan", yasi = 16, harfler = new[] {"a","b","c"}} 
           }; 
     DataTable dataTable = new DataTable(); 

     PropertyInfo[] pinfo = props(); 
     //var s = pinfo.Select(p => dataTable.Columns.Add(new DataColumn(p.Name, (p.PropertyType.FullName).GetType()))); 



     foreach (var p in pinfo) 
     { 
      dataTable.Columns.Add(new DataColumn(p.Name, p.PropertyType)); 
     } 

     foreach (Person person in lst) 
     { 
      DataRow dr = dataTable.NewRow(); 
      foreach (PropertyInfo info in person.GetType().GetProperties()) 
      { 
       object oo = person.GetType().GetProperty(info.Name).GetValue(person, null); 
       dr[info.Name] = oo; 
      } 
      dataTable.Rows.Add(dr); 
     } 

    } 

    static public PropertyInfo[] props() 
    { 
     return (new Person()).GetType().GetProperties(); 
    } 
} 

public class Person 
{ 
    public string adi { get; set; } 
    public int yasi { get; set; } 
    public string[] harfler { get; set; } 

} 
Questions connexes