Search code examples
c#v8system.dataclearscript

How do I update a column in a System.Data datarow using V8 under ClearScript?


I'm using the V8ScriptEngine

v8 = new V8ScriptEngine(V8ScriptEngineFlags.DisableGlobalMembers);

and have exposed the "System.Data" namespace into the ClearScript environment.

var htc = new HostTypeCollection();
foreach (var assembly in new string[] { "mscorlib", "System", "System.Core", "System.Data" })
{
    htc.AddAssembly(assembly);
}
...
v8.AddHostObject("CS", htc);

Then I've taken a System.Data example from Microsoft and have attempted to adapt it to the ClearScript/V8 environment

const DataTable = CS.System.Data.DataTable;
const DataColumn = CS.System.Data.DataColumn;
const DataRow = CS.System.Data.DataRow;

const table = new DataTable("Product");

// Create a DataColumn and set various properties.
const column = new DataColumn();
column.DataType = CS.System.Type.GetType("System.Decimal");
column.AllowDBNull = false;
column.Caption = "Price";
column.ColumnName = "Price";
column.DefaultValue = 25;

// Add the column to the table.
table.Columns.Add(column);

// Add 10 rows and set values.
let row;
for (let i = 0; i < 10; i++) {
    row = table.NewRow();
    row["Price"] = i + 1;

    // Be sure to add the new row to the
    // DataRowCollection.
    table.Rows.Add(row);
}

My difficulty at this point is that the row["Price"] = i + 1 works fine in C# context, but doesn't fare so well in ClearScript/V8, throwing a

Error: Object has no suitable property or field named 'Price'
    at Script:24:18 ->     row["Price"] = i + 1;

So the question is, how do I update a column in a row? I've gotten around this in earlier times by writing a helper function on the C# side. Is that still the best solution?


Solution

  • Instead of row["Price"] = i + 1, use row.Item.set("Price", i + 1). See here for an explanation.