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.7k
    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:

    using System.ComponentModel;

    Generic method:

    private DataTable ConvertToDataTable<T>(IList<T> list)
    {
        Type entityType = typeof(T);
        DataTable table = new DataTable();
    	PropertyDescriptorCollection properties =
    	   TypeDescriptor.GetProperties(entityType);
    	
    	foreach (PropertyDescriptor prop in properties)
    		table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    	foreach (T item in list)
    	{
    		DataRow row = table.NewRow();
    		foreach (PropertyDescriptor prop in properties)
    			row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
    		table.Rows.Add(row);
    	}
    	return table;
    
    }

     

    In VB.NET:
    Adding  namespace:

    Imports System.ComponentModel

    Generic method:

    Private Function ConvertToDataTable(Of T)(list As IList(Of T)) As DataTable
    	Dim entityType As Type = GetType(T)
    	Dim table As New DataTable()
    	Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(entityType)
    
    	For Each prop As PropertyDescriptor In properties
    		table.Columns.Add(prop.Name, If(Nullable.GetUnderlyingType(prop.PropertyType), prop.PropertyType))
    	Next
    	For Each item As T In list
    		Dim row As DataRow = table.NewRow()
    		For Each prop As PropertyDescriptor In properties
    			row(prop.Name) = If(prop.GetValue(item), DBNull.Value)
    		Next
    		table.Rows.Add(row)
    	Next
    	Return table
    
    End Function

    Hope this code will help you. Thanks

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: