Månad: november 2008

A DataTable helper

public class DBHelper
    {
        public static T RowToInstance<T>(DataRow row) where T : new()
        {
            T item = new T();
            Type t = item.GetType();
            foreach (PropertyInfo propInfo in t.GetProperties())
            {
                object temp = t.GetProperty(propInfo.Name).GetValue(item, null);
                System.Diagnostics.Debug.WriteLine(propInfo.Name);
                try { propInfo.SetValue(item, row[propInfo.Name], null); }
                catch { }
            }
            return item;
        }

        public static void LoadRowWithInstanceValues<T>(T item, ref DataRow row) where T : new()
        {           
            Type t = item.GetType();
            foreach (PropertyInfo propInfo in t.GetProperties())
            {
                object temp = t.GetProperty(propInfo.Name).GetValue(item, null);
                try { row[propInfo.Name] = propInfo.GetValue(item, null); }
                catch { }
            }           
        }  
    }

 

This handy piece of code helps you load a DataRow from a object or vice versa, Load a object with a DataRow. I use the get and setters in try catch block, it just loads propertys that have a matching column (name and datatype) in the DataTable the rest is simply ignored.

Annonser