Sunday, 25 August 2013

How to Convert Generic List to Datatable in C# Asp.Net





Description:-

                        In this Example we Explain that How to Convert List to Datatable in C# or asp.Net.now we First understand What is the List and DataTable in Asp.Net.

What is List in C# Asp.Net:-

            List is a one kind of Generic class provided by .Net is used for store Data in List Format for Category wise like only number,only string etc…

Through List we can Easily handle GropBy,Join or Add or Remove Item sorting Item or many other Operation.

What is DataTable in Asp.Net:-

            DataTable is one kind of Building Class Provided by Ado.Net and are used to store Table or Create a Datarow or DataColoumn at runtime and add to the DataTable.we can Easily add or Remove Datarow in Datatable.

Now we Expalin How to Convert List to Datatable in Asp.Net:

Here is a Code for Convert List to DataTable but before use this code you have to add the following Namespace like

using System.ComponentModel;

List<Employee> lstEmployee and want to convert in datatable then simply call this way.
Here List<Employee> is an one kind of List that I want to Convert in Datatable and lstEmployee is an object of the List<Employee> type


Implement Remember Me functionality using CheckBox ASP.Net 

set WaterMark Text in PDF using itextsharp in C#

How to set Default Button in MVC Web Form Application 

How to Bind XML File data to Treeview in asp.net

JQuery datepicker calender with Dropdown month and year in asp.net. 




Code for Convert List to Datatable:-




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.ComponentModel;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt = lstEmployee.ConvertToDataTable();
    }
    public static DataTable ConvertToDataTable<T>(IList<T> list) where T : class
    {
        try
        {
            DataTable table = CreateDataTable<T>();
            Type objType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor property in properties)
                {
                    if (!CanUseType(property.PropertyType)) continue;
                    row[property.Name] = property.GetValue(item) ?? DBNull.Value;
                }

                table.Rows.Add(row);
            }
            return table;
        }
        catch (DataException ex)
        {
            return null;
        }
        catch (Exception ex)
        {
            return null;
        }

    }
    private static DataTable CreateDataTable<T>() where T : class
    {
        Type objType = typeof(T);
        DataTable table = new DataTable(objType.Name);
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
        foreach (PropertyDescriptor property in properties)
        {
            Type propertyType = property.PropertyType;
            if (!CanUseType(propertyType)) continue;

            //nullables must use underlying types
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                propertyType = Nullable.GetUnderlyingType(propertyType);
            //enums also need special treatment
            if (propertyType.IsEnum)
                propertyType = Enum.GetUnderlyingType(propertyType);
            table.Columns.Add(property.Name, propertyType);
        }
        return table;
    }


    private static bool CanUseType(Type propertyType)
    {
        //only strings and value types
        if (propertyType.IsArray) return false;
        if (!propertyType.IsValueType && propertyType != typeof(string)) return false;
        return true;
    }
}

3 comments: