Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Add an Event Handler To the RowUpdated event in a table adapter

Tags:

c#

ado.net

I have a tableadapter and I want to do something when the RowUpdated event is fired. I can't figure out where to put the code to add the handler to the event.

public partial class MyTableAdapter
{
  void OnRowUpdated(object sender, System.Data.Odbc.OdbcRowUpdatedEventArgs e)
  {
  }
}

How do I get the code below to run when the TableAdapter is created?

Adapter.RowUpdated += 
                   new System.Data.Odbc.OdbcRowUpdatedEventHandler(OnRowUpdated);
like image 483
Simon Avatar asked Jul 14 '10 06:07

Simon


1 Answers

I resolved this in 2 stages.

a. add partial class and extend table adapter

b. call a method in the beginning before using this adapter (say in main form after you create instance of it).

The code below is to resolve my particular issue with SQL CE to be able to update IDs on the table. However you can use the extended method to wrap the RowUpdated event and expose it to other classes (ie MyRowUpdated)

The extension

public partial class ScannedItemsTableAdapter
{
    public void InitEvents()
    {
        this._adapter.RowUpdated += _adapter_RowUpdated;
    }

    void _adapter_RowUpdated(object sender, SqlCeRowUpdatedEventArgs e)
    {
        if (e.Status == UpdateStatus.Continue && 
            e.StatementType == StatementType.Insert)
        {
            var pk = e.Row.Table.PrimaryKey;
            pk[0].ReadOnly = false;

            SqlCeCommand cmd = new SqlCeCommand("SELECT @@IDENTITY", 
               e.Command.Connection, e.Command.Transaction);

            object id = (decimal)cmd.ExecuteScalar();

            e.Row[pk[0]] = Convert.ToInt32(id);
            e.Row.AcceptChanges();
        }
    }
}

The call in the main form:

        tableAdapter = new ScannedItemsTableAdapter();
        tableAdapter.Fill(ds.ScannedItems);
        tableAdapter.InitEvents();
like image 135
Boppity Bop Avatar answered Sep 28 '22 22:09

Boppity Bop