I’d like to define a class which is derived from System.Data.DataTable.
This class has a PopulateColumns method which as you can guess populate the DataTable.
I want this method to be able to dynamically populate the datatable columns with any number custom data types. (See my code below for clarification)
I tried using Dictionary<strin,Type>, instead of passing all the parameters one by one:
public void Populate(Dictionary<string, Type> dic)
{
foreach (var item in dic)
this.Columns.Add(item.Key, item.Value);
}
And Call it:
var testDt = new TestDataTable();
Dictionary<string, Type> dicCols = new Dictionary<string, Type>();
dicCols.Add("Index", System.Type.GetType("System.Int32"));
dicCols.Add("Title", System.Type.GetType("System.String"));
testDt.Populate(dicCols);
This works fine. but it cannot accept two columns with the same (Since column names are Keys in dictionary).
I know I don’t need to pass two columns with the same name. But I’m just curious if there’s a better way to do it.
It’s more simple than you think:
Or, you can build the list beforehand:
(Arrays, collections, etc. have an
AddRange()member.)