Using Reflection to create a DataTable from a Class?

后端 未结 9 1998
星月不相逢
星月不相逢 2020-12-02 07:39

I\'ve just learned about Generics and I\'m wondering whether I can use it to dynamically build datatables from my classes.

Or I might be missing the point here. Here

9条回答
  •  清歌不尽
    2020-12-02 08:07

    my favorite homemade function. it create and populate all at same time. throw any object.

     public static DataTable ObjectToData(object o)
     {
        DataTable dt = new DataTable("OutputData");
    
        DataRow dr = dt.NewRow();
        dt.Rows.Add(dr);
    
        o.GetType().GetProperties().ToList().ForEach(f =>
        {
            try
            {
                f.GetValue(o, null);
                dt.Columns.Add(f.Name, f.PropertyType);
                dt.Rows[0][f.Name] = f.GetValue(o, null);
            }
            catch { }
        });
        return dt;
     }
    

提交回复
热议问题