How to convert generic list to datatable in Asp.Net C#,VB

Introduction:  In this article I am going to explain how to convert list of string i.e. List<string> or List of object etc into datatable in Asp.Net with both C# and VB Language. 
Description: While working on Asp.Net project I got the requirement to convert List of string into datatable. Suppose there is a list of countries. There may be several reasons to convert list into datatable. After searching on google somewhere I found the solution for my problem and I am going to share the same with all so that someone in need get the solution on time.

Implementation: Let’s create an example to convert list of string into datatable for demonstration purpose. 

Asp.Net C# Code

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

protected void Page_Load(object sender, EventArgs e)
    {
        List<string> countries = new List<string>();
        countries.Add("USA");
        countries.Add("INDIA");
        countries.Add("JAPAN");
        countries.Add("CHINA");
        countries.Add("ENGLAND");
        DataTable dt = ListToDataTable(countries);
    }

    public static DataTable ListToDataTable<T>(IList<T> thisList)
    {
        DataTable dt = new DataTable();
        if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
        {
            DataColumn dc = new DataColumn("CountryList");
            dt.Columns.Add(dc);

            foreach (T item in thisList)
            {
                DataRow dr = dt.NewRow();
                dr[0] = item;
                dt.Rows.Add(dr);
            }
        }
        else
        {
            PropertyInfo[] propertyInfo = typeof(T).GetProperties();
            foreach (PropertyInfo pi in propertyInfo)
            {
                DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
                dt.Columns.Add(dc);
            }

            for (int item = 0; item < thisList.Count(); item++)
            {
                DataRow dr = dt.NewRow();
                for (int property = 0; property < propertyInfo.Length; property++)
                {
                    dr[property] = propertyInfo[property].GetValue(thisList[item], null);
                }
                dt.Rows.Add(dr);
            }
        }
        dt.AcceptChanges();
        return dt;

    }

Explanation: In above example i have created a list of countries. Then i have created a function that accepts List and returns datatable after converting.

Asp.Net VB Code

Imports System.Reflection
Imports System.Data

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim countries As New List(Of String)()
        countries.Add("USA")
        countries.Add("INDIA")
        countries.Add("JAPAN")
        countries.Add("CHINA")
        countries.Add("ENGLAND")
        Dim dt As DataTable = ListToDataTable(countries)
    End Sub


    Public Shared Function ListToDataTable(Of T)(thisList As IList(Of T)) As DataTable
        Dim dt As New DataTable()
        If GetType(T).IsValueType OrElse GetType(T).Equals(GetType(String)) Then
            Dim dc As New DataColumn("CountryList")
            dt.Columns.Add(dc)

            For Each item As T In thisList
                Dim dr As DataRow = dt.NewRow()
                dr(0) = item
                dt.Rows.Add(dr)
            Next
        Else
            Dim propertyInfo As PropertyInfo() = GetType(T).GetProperties()
            For Each pi As PropertyInfo In propertyInfo
                Dim dc As New DataColumn(pi.Name, pi.PropertyType)
                dt.Columns.Add(dc)
            Next

            For item As Integer = 0 To thisList.Count() - 1
                Dim dr As DataRow = dt.NewRow()
                For [property] As Integer = 0 To propertyInfo.Length - 1
                    dr([property]) = propertyInfo([property]).GetValue(thisList(item), Nothing)
                Next
                dt.Rows.Add(dr)
            Next
        End If
        dt.AcceptChanges()
        Return dt
    End Function

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.        
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..