Rejecting changes on DataTable.ColumnChanging event

S

SerGioGio

Hi !

I have a dataTable filled by a (oleDb) DataAdapter. The users can change the
dataTable (modifiy/add/delete rows) (it is connected to a DataGrid), and
when the click "commit", the changes are sent to the database thanks to
dataAdapter.Update.

This is working so far in most cases : DELETE / INSERT scenarios work well.
However, when the users modify the primary key columns in the DataTable, the
UPDATE statements are invalid, which is "normal", since the UPDATE
statements use the primary key columns (DataAdapter issues "UPDATE table SET
column='data' WHERE pk=<invalid-primary-key>"). I could set the primary key
columns to ReadOnly, but rather than that, I want to prevent my users from
changing primary keys for rows already set in the database, but allow them
changing primary keys as often as they want for rows not already commited in
the database.

This is why I trap the DataTable.ColumnChanging event : when the column is
part of the primary key, and the RowState is not "Added" or "Detached", I
don't make the proposed changes (i.e. I issue "proposedValue =
currentValue", I set the row column to error, etc.). Otherwise, I make the
changes to the column (i.e. I do nothing).

This is working. However, when I prevent changes from happing in the primary
key columns ("proposedValue = currentValue"), the dataTable *still* regards
this as a change (line in DataTable.GetChanges()), the RowState is
"Modified", and eventually the DataAdapter will issue a useless SQL
statement. I don't know how to tell the dataTable to discard *this* change
on *this* column only.

There seems to be a validating phase in when you enter data in a
DataGrid/DataTable. For example, if your data is too large for the column,
you will have a message saying it, the data will be reversed back to its
original value, and the row won't go into a "Modified" state... However I
don't know how to trap this validation phase.

Thanks in advance for your suggestions and comments !

SerGioGio
 
M

Miha Markic

Hi,

Try throwing an exception within ColumnChanging event when you want to
cancel the change.
 
S

SerGioGio

Hi Miha,

Thanks for your quick answer.
I tried that, but the DataRow is still in "Modified" state.

Regards,

SerGioGio
 
S

SerGioGio

Hi Miha,

I am sure. When "ColumnChanging" is trapped, RowState is still "Unchanged".
I throw a System.Exception, and something (not my code) catches it. After
that, RowState is "Modified". I change only one column, and I get only one
"ColumnChanging" event.

However is throwing an exception the official solution to my problem
(documented anywhere...?) ?

Regards,

Serge
 

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