Jonny
Jonny

Reputation: 401

Dynamically add data to column

So i had to make a running balance column based on an existing data table.

I have the formulas and everything.

I would just like to know if it is possible to make another column in that data table and generically add data to it based on the result of the formula,

currently I loop through the table row by row and equate the last column, can I put the result in that same row?

Thanks everyone

Upvotes: 0

Views: 1373

Answers (3)

thevan
thevan

Reputation: 10364

DataColumn newColumn = new DataColumn("ColumnName", typeof(System.String));  // I considered the column datatype as string, u can give as u want
newColumn.DefaultValue = "Your Value";
dataTable.Columns.Add(newColumn);

We can add a new column with default value as above.. If you want add some other value means, go for for-loop or foreach..

foreach (DataRow DR in dataTable.Rows)
{
     DR["ColumnName"] = "Your Value";
}

Upvotes: 1

Vikram Jain
Vikram Jain

Reputation: 5588

 Also refer [MSDN][1]   

// Create total column.
DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Decimal");
totalColumn.ColumnName = "total";
totalColumn.Expression = "Price+ Quantity";

// Add columns to DataTable.
...
table.Columns.Add(totalColumn);

Upvotes: 0

Raja Nadar
Raja Nadar

Reputation: 9499

Yes, you can add a new column to the data table any time, and once added, can always set the value of the RunningBalance cell (column + row) to the value you calculated.

DataColumn runningBalanceColumn = myDataTable.Columns.Add("RunningBalance", typeof(Int64));

runningBalanceColumn[0] = RUNNING_BALANCE_FOR_FIRST_ROW;
// and so on

Upvotes: 0

Related Questions