Click here to Skip to main content
13,248,927 members (45,319 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked
Posted 23 Jan 2013

Calculated Columns in .NET DataTables (C#)

, 23 Jan 2013
Rate this:
Please Sign up or sign in to vote.
Adding Calculated Columns in .NET DataTables.

Recently I had a requirement to add Calculated Columns to a DataTable. For example, I’m only providing Amount and Quantity. Then discount will be calculated automatically.

String Discount = ".1";
DataTable workTable = new DataTable("Customers");

DataColumn workCol = workTable.Columns.Add("ID", typeof(Int32));
workTable.Columns.Add("UnitPrice", typeof(Double));
workTable.Columns.Add("Quantity", typeof(Int16));
workTable.Columns.Add("Total", typeof(Double));
workTable.Columns.Add("Discount", typeof(Double));

workTable.Columns["Total"].Expression = "UnitPrice*Quantity";
workTable.Columns["Discount"].Expression = String.Format("Total*{0}",Discount);

Later you can bind the DataTable to a GridView if you need.

dataGridView1.DataSource = workTable;

Special note:

But my requirement was to update the Column Expression dynamically in the runtime. For an example Discount will be change according to the total amount. Therefore this method can not cater that requirement since  expression is fixed with the discount.

Thus I update the Column Expression in dataGridView1_DataBindingComplete and invalidate the control for force data panting.

Double RunningSum = 0;
String ValDiscount = "50";
workTable.Columns["ValueDis"].Expression = 
   String.Format("{0}/{1}*Total", ValDiscount, RunningSum.ToString());


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sri Lanka Sri Lanka
No Biography provided

You may also be interested in...

Comments and Discussions

SuggestionFormatting... Pin
Sandeep Mewara26-Aug-12 4:39
mvpSandeep Mewara26-Aug-12 4:39 
Post formatting, looks like it would fit more as a Tip than blog.

Format and post it as a Tip/Trick.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 23 Jan 2013
Article Copyright 2013 by Melick
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid