ImportRow to DataTable with reference to a new row

The MS .Net framework DataTable.ImportRow doesn't return reference to a new row.

Also it is not documented how ImportRow will behave if record with primary keys already exist.  

So I've created a static "overload" of DataTable.LoadDataRow  method.

 

 

The common mistake that I had was that DataTable didn't have schema filled, and primary keys were empty. It caused that even existing records were considered as new, and duplicates were imported. So I've added a CheckPrimaryKey parameted, which is recommended set to true unless you expected tables without primary keys.

     

        /// <summary>

        /// Static "overload" of <see cref="DataTable.LoadDataRow"/> method.

        ///Finds and updates a specific row. If no matching row is found, a new row is created using the given values.

        /// </summary>

        /// <param name="tbl"></param>

        /// <param name="row"></param>

        /// <returns></returns>

        /// <remarks >The MS .Net framework DataTable.ImportRow doesn't return reference to a new row.

        ///Also it is not documented how ImportRow will behave if record with primarykeys already exist.</remarks>

        public static DataRow LoadDataRow(DataTable tbl,    DataRow row, bool CheckPrimaryKey)

        {

            if (CheckPrimaryKey == true)

            {

                if ((tbl.PrimaryKey == null) || (tbl.PrimaryKey.Length == 0))

                {

                    Debug.Assert(false);

                    return null;

                }

            }

           DataRow newRow = tbl.LoadDataRow(row.ItemArray,false);

            return newRow;

        }

posted @ Wednesday, August 02, 2006 12:38 PM

Print

Comments on this entry:

# re: ImportRow to DataTable with reference to a new row

Left by sangam at 12/15/2008 1:07 AM
Gravatar
Thank you for the trick. I am using the ImportRow method to copy row from one datatable to another datatable and the particular scenario you present is really appreciable. Thanks again.

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345