Saturday, April 28, 2007

Custom formatting in DataAdapter.Update

Here is the scenario. I have a datatable that has a datetime column and i am using DataAdapter.Update(dataTable) method, to persist the changes back to the database. The default implementation of this method, for some reason, truncates the milliseconds when saving the values to the database. How do I get around this, but still leverage the ease-of-use and performance that the DataAdapter provides? Here is one possible (and simple) solution.

private void WriteChanges(DataTable dataTable )
{
aeAdapter.RowUpdating += new SqlCeRowUpdatingEventHandler(adapter_RowUpdating);
aeAdapter.Update(copyTable);
}

void adapter_RowUpdating(object sender, SqlCeRowUpdatingEventArgs e)
{
e.Command.Parameters["@Updated"].Value = FormatDate(e.Row["Updated"]);
}


private string FormatDate(object datetime)
{
if (datetime == null Convert.IsDBNull(datetime)) return "";
DateTime value = Convert.ToDateTime(datetime);
return value.ToString (System.Globalization.DateTimeFormatInfo.InvariantInfo) + "." + value.Millisecond.ToString();
}