monther zlatan
monther zlatan

Reputation: 156

fixing datatable to list convertion code

I am Trying to convert DataTable To List I found this code in stackoverflow I use it unfortunatley it render same rows number but with empty fields anyone know what's wrong with it ?

public static class Helper
{
/// <summary>
/// Converts a DataTable to a list with generic objects
/// </summary>
/// <typeparam name="T">Generic object</typeparam>
/// <param name="table">DataTable</param>
/// <returns>List with generic objects</returns>
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
    try
    {
        List<T> list = new List<T>();

        foreach (var row in table.AsEnumerable())
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                    propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                }
                catch
                {
                    continue;
                }
            }

            list.Add(obj);
        }

        return list;
    }
    catch
    {
        return null;
    }
}
}

Upvotes: 1

Views: 72

Answers (2)

OverBakedToast
OverBakedToast

Reputation: 147

I've created a similar method that does just that. Make sure you have a model set up for the DataTable you are trying to cast to and pass that in as the type.

public static List<T> DataTableToList<T>(DataTable data)
{
    List<T> list = new List<T>();
    PropertyInfo[] props = typeof(T).GetProperties();
    foreach (DataRow dr in data.Rows)
    {
        T obj = (T)Activator.CreateInstance(typeof(T));

        foreach(PropertyInfo prop in props)
        {
            object value;

            if (prop.PropertyType == typeof(bool))
                value = Convert.ToBoolean(Convert.ToInt16(dr[prop.Name]));
            else
                value = dr[prop.Name];

            obj.SetPropValue<object>(prop.Name, value);
        }

        list.Add((T)obj);
    }
    return list;
}

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

your object property name should be similar to name of column..so please change name of your object similar to name of your database table column

Because this code is putting value for those property for which matching columns found in database.

Upvotes: 3

Related Questions