Update: The DataTable meets dynamic - improved!

12. februar 2010

A few days ago I blogged about a tiny fun project of mine, where I added dynamic type support to the DataTable and DataRow classes.

This was fun, and the code works as intended, but it has a two shortcomings: There was a bug preventing you from setting values of regular properties on the DynamicDataRow type, and you couldn't add new columns using dynamic properties.

Naturally, I had to fix this, so here it is: The DynamicDataTable v2!

What is new?

Most of the code is the same as last time, but this time the useage is even simpler. You just create a new DynamicDataTable object, add a new row using the NewRow method and assign values to the properties you need. Look at this:

// Create a DataTable
var tb = new DynamicDataTable();

// Row using dynamic syntax
dynamic row = tb.NewRow();
row.aa = "Dynamic here!";
row.bb = 44;
row.cc = DateTime.Now; 
tb.Rows.Add(row);

// Access column values using property accessors instead of using the indexer
Console.WriteLine("AA: " + row.aa);
Console.WriteLine("BB: " + row.bb);
Console.WriteLine("CC: " + row.cc);

If you compare this with the previous version you see that I have removed the column definitions. Now when the DynamicDataRow intercepts a call to a property set for a property that doesn't exist it will check its DataTable to see if there is a column with that name. If it can't find a column with that name it will add a new column and set its datatype to the type of the assigned value. In the above example our table ends up with three columns: "aa" of type String, "bb" of type Int32 and "cc" of type DateTime. Later you can access the DataTable as a regular table if you want.

The updated source code

I have uploaded an updated version of the source code if you are interested: DynamicDataTable.zip (4.57 kb)

kick it on DotNetKicks.com

.NET

Comments

12.02.2010 11:10:50 #
Update: The DataTable meets dynamic - improved!

You've been kicked (a good thing) - Trackback from DotNetKicks.com
27.07.2012 07:37:18 #
Must say good one to go through. Bookmarking this site to come back again. Thanks for sharing.
06.02.2018 05:51:54 #
I’m trampled by your contents carry on the wonderful work.
23.02.2018 11:17:19 #
Personally I think overjoyed I discovered the blogs.
24.02.2018 08:07:34 #
I feel happiness to read the content that you are posting.

Add comment




  Country flag

The number (5) not with letters. This is to stop spammers.

biuquote
  • Comment
  • Preview
Loading