Note : This post is first published on Nov-2011 in my previous blog Techkindle. Moving the content here.
DataRowState : Its a state corresponding to each row in DataTable.
Consider the following scenario, we have a set of records in DB and from the User Interface we need to provide the facility for user to update any existing records or to add any new records. But, this set of changed records need to send to the DB all at once (i.e for example on a Button Click event), Till that time we need to retain all the records at our page itself. and user also have an option to cancel these changes.
So, while sending all the records to DB at once, we need to find a way to check which row is to be inserted, and which row need to be updated in DB, one option is to maintain one more column in the table as flag, but its very difficult to maintain these flags. another option is to take the advantage of the DataRowState (if we assume records will be maintained in the DataTable). Each row will be having a State (like Added, Unchanged, Modified etc..), using this States we can easily find out which row should be saved and which row should be updated.
DataRowState is very much useful in this kind of scenarios.
First we will look at the different states present in DataRowState,
- Added The row has been added to a DataRowCollection, and AcceptChanges has not been called.
- Modified The row has been modified and AcceptChanges has not been called.
- UnChanged The row has not changed since AcceptChanges was last called.
- Detached The row has been created but is not part of any DataRowCollection. A DataRow is in this state immediately after it has been created and before it is added to a collection, or if it has been removed from a collection.
- Deleted The row was deleted using the Delete method of the DataRow.
The below is the example with the all states.
The output will be as follows:
In the above output we can see that , at last the changes are canceled, but still one of the row is not exist.this is because it has got removed(not deleted).we cannot get the records back once we use Remove. but if we use Delete, still we can get our records back.
Happy Learning 🙂