Kamyar
Kamyar

Reputation: 18797

Populate Datatable columns with custom types

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.

Upvotes: 2

Views: 8720

Answers (1)

SnickersAreMyFave
SnickersAreMyFave

Reputation: 5143

It's more simple than you think:

    testDt.Columns.AddRange(new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    });

Or, you can build the list beforehand:

    var columns = new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    };

    testDt.Columns.AddRange(columns);

(Arrays, collections, etc. have an AddRange() member.)

Upvotes: 7

Related Questions