views:

65

answers:

1

There are three columns in the datatable

Amount Commission Others
1000   200        100
2000   100        200

Now I want to build another column based on these three columns name totalAmount that is the sum of these three columns like the column will be

totalAmount
1300
2300

I got the records of the three columns Amount,Commission and Others and based on those columns I have a need of adding a new column in that datatable.We can manuall fetch and make total and add a new column in that datatable but is there any other good and short way ?

+1  A: 

Check out the DataColumn.Expression property.

You can add a new DataColumn to your table, and set its Expression to "Amount + Commission + Others". It'll be calculated at runtime.

Matt Hamilton
@Matt Hamilton,Would this add only column or records also ?
Harikrishna
It won't add records. It's a column whose value is computed using other columns. You'll get a new value for every existing row.
Matt Hamilton
@Matt Hamilton,But if we create the column like `DataColumn totalAmount=new DataColumn("totalAmount",typeof(int),"");``TableExtractedFromFile.Columns.Add(totalAmount);`then it gives error.
Harikrishna
Really? How about TableExtractedFromFile.Columns.Add("totalAmount", typeof(int), "Amount + Commission + Others"); ?
Matt Hamilton
Are you doing this before or after you populate the table? I can't even remember if it matters, to be honest. Haven't used DataTable for years.
Matt Hamilton
@Matt Hamilton,It works. But If I do like there is three columns A,B and C. Now if do I `table.columns["A"].expression = "A+B+C";` then it gives error like **Cannot set Expression property due to circular reference in the expression.** then what is the solution of that ?
Harikrishna
What are you trying to do? You can't set a column to an expression that includes itself.
Matt Hamilton
@Matt Hamilton,But sir, If I want to make addition of the values of three columns like column A,B,C and want to store those values in the column A the what should I do?
Harikrishna
@Matt Hamilton,Even I copy of the column A and add new column AA then B+C+AA then also it gives same error.
Harikrishna