Introduction
Function to Convert Hashtable Rows into DataTable Columns in C#
Background
Hashtable, DataSet, DataRow,DictionaryEntry etc.
Using the Code
Simplest way to convert a Hashtable into a DataTable with all the Hashtable rows converted into DataTable columns. This code creates one row in DataTable, you can modify it according to your requirement.
This Function returns a DataTable
object and takes a Hashtable
object as parameter. Simple implementation example:
htData <Hashtable with Data>
DataTable dt =new DataTable();
dt= ConvertHashtableRowsToDataTableColumns(htData);
The classes used are:
DataTable
, DictionaryEntry
, DataRow
, object
, var
and Hashtable
.
the methods and properties, used are:
-
dataTable.Columns.Add(entry.Key.ToString(), typeof(object));
-
entry.Value.ToString()
dataTable.Rows.Add(dr)
dataTable.NewRow()
ht.GetType().Name
and dataTable.TableName
, used to specify the table name.
private DataTable ConvertHashtableRowsToDataTableColumns(System.Collections.Hashtable ht)
{
var dataTable = new DataTable(ht.GetType().Name);
dataTable.TableName = "TableName";
foreach (DictionaryEntry entry in ht)
{
dataTable.Columns.Add(entry.Key.ToString(), typeof(object));
}
DataRow dr = dataTable.NewRow();
foreach (DictionaryEntry entry in ht)
{
dr[entry.Key.ToString()] = entry.Value.ToString();
}
dataTable.Rows.Add(dr);
return dataTable;
}
Hope this helps in time of need...
Happy Coding