2009-07-20 3 views
0

개체의 속성을 DataTable로 자동 변환하려고합니다 (개체가 배열이고 값 형식이있는 특수 클래스에서 인스턴스화 된 속성이 있음).직렬화 가능한 배열 데이터를 DataColumn에 저장할 수 있습니까?

코드 :

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; 
} 

내가 DataColumn에이 배열을 저장하기 위해 어떻게해야합니까?

+1

System.Object 형식을 사용해보십시오. –

답변

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; } 

} 
관련 문제