Link to home
Start Free TrialLog in
Avatar of IvanHowarth
IvanHowarth

asked on

How do you create a new DataTable column expression using a column name and a variable?

How do you create a new DataTable column expression using a columnName * variableName?

The following gives creates a new column, and an expression of MyColumn * (a fixed value)

       ' Create the new column.
        Dim MyNewColumn As New DataColumn
        MyNewColumn.ColumnName = "MyColumnName"
        MyNewColumn.Expression = "AnotherColumnName * 7"

        ' Add column to DataTable
        Me.MyDataSet.MyDataTable.Columns.Add(MyNewColumn)
     
In the above example, I am after the 7 being a variable, not a predetermined fixed value.
Avatar of Nandakumar Sakthivel
Nandakumar Sakthivel
Flag of United States of America image

ASKER CERTIFIED SOLUTION
Avatar of arif_eqbal
arif_eqbal

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Try this.,

 Dim x As Integer = 9  // assign the value that you want to multiply with the column here

Dim ds As New DataSet
Dim dt As New DataTable
Dim dr As DataRow

Dim column1 As New DataColumn
column1.ColumnName = "Number"
column1.DataType = GetType(Integer)
dt.Columns.Add(column1)

Dim column2 As New DataColumn
column2.ColumnName = "MinValue"
column2.DataType = GetType(Integer)
dt.Columns.Add(column2)

Dim column3 As New DataColumn
column3.ColumnName = "TotalValue"
column3.DataType = GetType(Integer)
column3.Expression = String.Format("Number * {0}", x)
dt.Columns.Add(column3)

dr = dt.NewRow
dr.item(0) = 5
dr.item(1) = 10
dt.Rows.Add(dr)

dr = dt.NewRow
dr.item(0) = 20
dr.item(1) = 30
dt.Rows.Add(dr)

Thanks,
Nanda
Avatar of IvanHowarth
IvanHowarth

ASKER

arif_eqbal  answer was exactly what I needed.

Thanks both anyway.