DataTable.Add(row) and fired events

C

Chris Alm

I have a situation where a method listens to the RowChanged event for a
datatable. The problem I having is this..

The RowChanged event handler calls another method, passing in the
e.Row["ID_VALUE"] of the row that fired the event.

In the case where this is a .Add(dr) that has caused the RowChanged event to
fire.... the row that is referenced in e.Row (event arg for the RowChanged
event handler) is not actually in the table yet.

If I do a dt.Select() or a dt.Rows.Count,,, it is obvious that the row
firing the event has not actually been added to table yet.

Why is this happening? Is this a bug? Why would the row fire the table event
and not be in the Rows collection for the table???
 
G

Guest

Hi Chris. I have just come across the same "problem". The event is indeed
fired before the row is added to the table's DataRowCollection - the event is
raised by the (internal) method SetNewRecord(). I really would like too see a
RowAdded event or similar.

fyi, here is my post from another board:

Further to my earlier mail, below is some demo code which explains why I am
not seeing any rows within the event itself. Thought I'd share fwiw.

using System;
using System.Data;

namespace eventdemo
{
class Class1
{
static void Main()
{
// create the table
DataTable dt=new DataTable();
dt.Columns.Add("Col1",typeof(System.Int32));
dt.RowChanged+=new DataRowChangeEventHandler(dt_RowChanged);

// here is the test
Console.WriteLine("Main: Table has {0} rows",dt.Rows.Count);
dt.Rows.Add(new object[] {1});
Console.WriteLine("Main: Table has {0} rows",dt.Rows.Count);
}
private static void dt_RowChanged(object sender, DataRowChangeEventArgs e)
{
Console.WriteLine("dt_RowChanged: Table has {0}
rows",e.Row.Table.Rows.Count);
}
}
}

The output of the code is:

Main: Table has 0 rows
dt_RowChanged: Table has 0 rows
Main: Table has 1 rows

Looking at the call stack within the event itself and using Reflector I see
that DataTable.SetNewRecord() is fired before the row is added to the inner
list of the DataRowCollection, which is not the behaviour I expected:

eventdemo.exe!eventdemo.Class1.dt_RowChanged(..)
system.data.dll!System.Data.DataTable.OnRowChanged(..)
system.data.dll!System.Data.DataTable.RaiseRowChanged(..)
system.data.dll!System.Data.DataTable.SetNewRecord(..)
system.data.dll!System.Data.DataTable.InsertRow(..)
system.data.dll!System.Data.DataTable.AddRow(..)
system.data.dll!System.Data.DataRowCollection.Add(..)
eventdemo.exe!eventdemo.Class1.Main(..)

Cheers

kh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top