Create Item DataRow - CSharp System.Data

CSharp examples for System.Data:DataRow

Description

Create Item DataRow

Demo Code


using System.Reflection;
using System.ComponentModel;
using System.Collections;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from  ww  w. j a  v a2 s  . c om

public class Main{
        public static T CreateItem<T>(DataRow row)
        {
            T obj = default(T);
            if (row != null)
            {
                obj = Activator.CreateInstance<T>();

                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
               
                    object value = row[column.ColumnName];
                    //prop.SetValue(obj, value, null);
                    if (value != DBNull.Value)
                    {
                        if (prop.PropertyType == typeof(decimal))
                            prop.SetValue(obj, decimal.Parse(value.ToString()), null);
                        else if (prop.PropertyType == typeof(int))
                            prop.SetValue(obj, int.Parse(value.ToString()), null);
                        else if (prop.PropertyType == typeof(float))
                            prop.SetValue(obj, float.Parse(value.ToString()), null);
                        else if (prop.PropertyType == typeof(DateTime))
                            prop.SetValue(obj, Convert.ToDateTime(value.ToString()), null);
                        else
                            prop.SetValue(obj, value, null);
                    }
                    else
                        prop.SetValue(obj, null, null);
                    
                }
            }

            return obj;
        }
}

Related Tutorials