views:

156

answers:

1

Hi,

How can I update the column value (programmatically) in a Row of a DataTable via use of the RowChanged event, without triggering infinite loop? (which I currently get)

Note I do not want to use the DataColumn.Expression property.

For example the following gives me a recursive loop and stack overflow error:

    DataColumn dc = new DataColumn("OverallSize", typeof(long));
    DT_Webfiles.Columns.Add(dc);
    DT_Webfiles.RowChanged += new DataRowChangeEventHandler(DT_Row_Changed);

private static void DT_Row_Changed(object sender, DataRowChangeEventArgs e)
{
    Console.Out.WriteLine("DT_Row_Changed - Size = " + e.Row["OverallSize"]);
    e.Row["OverallSize"] = e.Row["OverallSize"] ?? 0;
    e.Row["OverallSize"] = (long)e.Row["OverallSize"] + 1;
}

thanks

PS. In fact using the RowChanging event (rather than RowChanged) makes sense to me (i.e. change the value before it saves so to speak) however when I try this I get a "Cannot change a proposed value in the RowChanging event" at the following line in the handler:

e.Row["OverallSize"] = e.Row["OverallSize"] ?? 0;
+1  A: 

You could unsubscribe when within the event handler, though that would make your code not thread-safe.

DataColumn dc = new DataColumn("OverallSize", typeof(long));
DT_Webfiles.Columns.Add(dc);
DT_Webfiles.RowChanged += new DataRowChangeEventHandler(DT_Row_Changed);

private static void DT_Row_Changed(object sender, DataRowChangeEventArgs e)
{
    e.RowChanged -= new DataRowChangeEventHandler(DT_Row_Changed);
    Console.Out.WriteLine("DT_Row_Changed - Size = " + e.Row["OverallSize"]);
    e.Row["OverallSize"] = e.Row["OverallSize"] ?? 0;
    e.Row["OverallSize"] = (long)e.Row["OverallSize"] + 1;
    e.RowChanged += new DataRowChangeEventHandler(DT_Row_Changed);
}
Dan Herbert
thanks Dan - do you think there is a completely different approach I should be looking at re best practice? (and to make thread safe)
Greg