Umair Arif
Umair Arif

Reputation: 117

Datatable to Generic List Conversion

I want to create a Generic function to which I pass Model/ViewModel class and that function will convert Datatable to the List of that Model/ViewModel, I have tried the following code but it gives me an error for Null values, which I have mentioned below.

public static List<T> ConvertDataTable<T>(DataTable dt)
{
    List<T> data = new List<T>();
    foreach (DataRow row in dt.Rows)
    {
        T item = GetItem<T>(row);
        data.Add(item);
    }
    return data;
}
private static T GetItem<T>(DataRow dr)
{
    Type temp = typeof(T);
    T obj = Activator.CreateInstance<T>();

    foreach (DataColumn column in dr.Table.Columns)
    {
        foreach (PropertyInfo pro in temp.GetProperties())
        {
            //if (column.ColumnName == "CreatedOn" || column.ColumnName == "ModifiedOn")
            //    continue;

            if (pro.Name == column.ColumnName)
                if(dr[column.ColumnName] != null)
                    pro.SetValue(obj, dr[column.ColumnName], null);
                else
                    continue;
            }
        }
    return obj;
}

Calling:

public List<WordInfo> GetData()
{
    DataTable data = _wordsDL.Get("GetAll");
    return Helper.ConvertDataTable<WordInfo>(data);
}

Object of type 'System.DBNull' cannot be converted to type 'System.String'.'

Upvotes: 2

Views: 834

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39946

You need to check for DBNull.Value instead, something like this:

if (dr[column.ColumnName] != DBNull.Value)
    pro.SetValue(obj, dr[column.ColumnName], null);

Or:

pro.SetValue(obj, dr[column.ColumnName] == DBNull.Value ? string.Empty : 
      dr[column.ColumnName].ToString(), null);

Upvotes: 4

Related Questions