Monday, October 22, 2012

Playing with Datatable class in C#.net

DataTable object represent data in a tabular format in memory. We often use DataTable as disconnected ADO.NET object. We will discuss about common scenario and mistakes that is frequently occurred by developers and end of the day we loss our valuable working hours.

Issue 1: Adding rows into DataTable from another similar structured DataTable

Very often we need to add datarows from from one datable to another one with similar type of structure.
This sounds pretty easy to code like :    
     
But those above lines of code will throw an exception.This is because a datarow passess through different states and we need to know about the state of datarow before we can assign it to another datatable.
The DataRowState values are described in Table below :


ROWSTATE VALUE
DESCRIPTION

Detached
The data row has been created but not added to a data table.
Added
The data row has been created and added to the data table.
Unchanged
The data row has not changed since the last call to the
AcceptChanges
method. When the AcceptChanges method is
called, the data row changes to this state.
Modified
The data row has been modified since the last time the
AcceptChanges
method was called. Adding a row and modifying
the row will keep the row in the Added state. The row changes to
the Modified state only if it was previously in the Unchanged state.
Deleted
An attached data row is deleted by using the Delete method of the
DataRow object or when it is removed from its table by calling the
DataTable.DeleteRow method.

You can read the RowState property of the data row at any time to determine the current
state of the data row. Below the figure shows the RowState transitions at different times in the
DataRow object’s life.






Another way to import the row value is accessing the  Itemarray of the datarow from the first table as below :


The above code block will solve the purpose but it might be complex for some scenario. It is better to use the nice feature of import method in the datatable class :

 

Notice that I didn't initialized the columns with names and  assigned value with column index not using column name. The reason is if the column name is different then ImportRow method with not work


No comments:

Post a Comment

Rest Service using WEB API C#

This post will show a simple example of REST service built on Micrsoft WEB API framework. WEB API is an extensible framework from microsof...