posted on Monday, June 19, 2006 2:35 PM by warstar

Object to DataTable

Hi all, Did you ever had the problem that u just wanted your object in a datatable and didn't wane hardcode the datatable if so this may help:

#region ObjectArrayToDataTable
        internal static DataTable ObjectArrayToDataTable(object[] obj, Type type)
        {
            return ObjectArrayToDataTable(obj, type, null);
        }
        internal static DataTable ObjectArrayToDataTable(object[] obj, Type type, DataColumn[] extra)
        {
            DataTable dt = new DataTable();

            foreach (PropertyInfo pi in type.GetProperties())
            {
                if (pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(string) || pi.PropertyType == typeof(DateTime))
                {
                    dt.Columns.Add(pi.Name, pi.PropertyType);
                }
            }

            if (extra != null)
            {
                foreach (DataColumn c in extra)
                {
                    if (dt.Columns.Contains(c.ColumnName))
                        dt.Columns.Remove(c.ColumnName);
                    dt.Columns.Add(c);
                }
            }

            foreach (object k in obj)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in type.GetProperties())
                {
                    if (pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(string) || pi.PropertyType == typeof(DateTime))
                    {
                        dr[pi.Name] = pi.GetValue(k, null);
                    }
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }
        #endregion

I wish you all happy netting!

Comments