Geeks With Blogs

News My Blog has been MOVED to https://mfreidge.wordpress.com
Michael Freidgeim's OLD Blog My Blog has been MOVED to https://mfreidge.wordpress.com

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 on Wednesday, August 2, 2006 12:38 PM .Net Framework | Back to top


Comments on this post: ImportRow to DataTable with reference to a new row

# re: ImportRow to DataTable with reference to a new row
Requesting 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.
Left by sangam on Dec 15, 2008 1:07 AM

Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net