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