HelpASisterOut
HelpASisterOut

Reputation: 3185

Append a column to an existing Datatable with dynamically bound values

I have the following Datatable in Vb

   Id            Price
  -----          -------
   1231           100
   1232           150
   1235           150

I want to add a third column to that datatable called flag, with values of the last digit of Id

Like the following:

    Id               Price         Flag
   -----            ------       ----------
    1231             100             1
    1232             150             2
    1235             150             5

How do I append a column to an existing Datatable, with dynamically bound values?

Is there a way I can do this without using a For Loop?

Any help would be appreciated

Upvotes: 1

Views: 4740

Answers (2)

Is there a way I can do this without using a For Loop?

Yes, add a computed column with the following expression:

[id] % 10

Example (vb.net):

Using table As New DataTable()

    table.Columns.Add("Id", GetType(Integer))
    table.Columns.Add("Price", GetType(Decimal))

    table.Rows.Add(1231I, 100D)
    table.Rows.Add(1232I, 150D)
    table.Rows.Add(1235I, 150D)

    'Add a new computed column:                    expr
    table.Columns.Add("Flag", GetType(Integer), "[id] % 10")

    For Each row As DataRow In table.Rows
        Debug.WriteLine("{0}    {1}    {2}", row.ItemArray)
    Next

End Using

Example (C#):

using (DataTable table = new DataTable())
{

    table.Columns.Add("Id", typeof(int));
    table.Columns.Add("Price", typeof(decimal));

    table.Rows.Add(1231, 100M);
    table.Rows.Add(1232, 150M);
    table.Rows.Add(1235, 150M);

    //Add a new computed column:              expr
    table.Columns.Add("Flag", typeof(int), "[id] % 10");

    foreach (DataRow row in table.Rows)
    {
        Debug.WriteLine("{0}    {1}    {2}", row.ItemArray);
    }

}

Output:

1231    100    1
1232    150    2
1235    150    5

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460208

You first need to add a DataColumn:

table.Columns.Add("Flag", typeof(int));

Now you just need to add the values accordingly:

foreach(DataRow row in table.Rows)
{
    int ID = row.Field<int>("ID");
    string lastDigit = ID.ToString().Last().ToString();
    row.SetField("Flag", int.Parse(lastDigit));
}

The only way to avoid a loop is to fill it with these values in the first place, for example if it's filled from database. So even if a DataColumn.Expression approach existed(which is not the case here) that would cause a loop in the framework.

Upvotes: 2

Related Questions