how to convert list to datatable in c#

Description:
First of all create the Function for convert data from List to Datatable as below.
        static DataTable ConvertListToDataTable(List<string[]> list)
        {
            DataTable table = new DataTable();
            int columns = 0;
            foreach (var array in list)
            {
                if (array.Length > columns)
                {
                    columns = array.Length;
                }
            }
            for (int i = 0; i < columns; i++)
            {
                table.Columns.Add();
            }
            foreach (var array in list)
            {
                table.Rows.Add(array);
            }
            return table;
         }
         
Now bind the List and convert into DataTable using above function as below. 
List<string[]> list = new List<string[]>();
//Bind the List here
DataTable table = ConvertListToDataTable(list);

No comments:

Post a Comment