Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Convert List to DataTable in C# and VB.NET

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 14.9k
    Comment on it

    In this blog I described how to convert list objects to DataTable. There are several method to convert list objects to DataTable. In this blog I used List interface for conversion.
    It is a generic method, it converts all types of list into DataTable. <T> defines the type of list.

    In C#
    Adding  namespace:

    1. using System.ComponentModel;

    Generic method:

    1. private DataTable ConvertToDataTable<T>(IList<T> list)
    2. {
    3. Type entityType = typeof(T);
    4. DataTable table = new DataTable();
    5.     PropertyDescriptorCollection properties =
    6.      TypeDescriptor.GetProperties(entityType);
    7.     
    8.     foreach (PropertyDescriptor prop in properties)
    9.         table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    10.     foreach (T item in list)
    11.     {
    12.         DataRow row = table.NewRow();
    13.         foreach (PropertyDescriptor prop in properties)
    14.             row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
    15.         table.Rows.Add(row);
    16.     }
    17.     return table;
    18.  
    19. }

     

    In VB.NET:
    Adding  namespace:

    1. Imports System.ComponentModel

    Generic method:

    1. Private Function ConvertToDataTable(Of T)(list As IList(Of T)) As DataTable
    2.     Dim entityType As Type = GetType(T)
    3.     Dim table As New DataTable()
    4.     Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(entityType)
    5.  
    6.     For Each prop As PropertyDescriptor In properties
    7.         table.Columns.Add(prop.Name, If(Nullable.GetUnderlyingType(prop.PropertyType), prop.PropertyType))
    8.     Next
    9.     For Each item As T In list
    10.         Dim row As DataRow = table.NewRow()
    11.         For Each prop As PropertyDescriptor In properties
    12.             row(prop.Name) = If(prop.GetValue(item), DBNull.Value)
    13.         Next
    14.         table.Rows.Add(row)
    15.     Next
    16.     Return table
    17.  
    18. End Function

    Hope this code will help you. Thanks

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: