Tuesday 25 September 2007

Using DataAdapter.Update on DataTable when using a BindingSource

I had a weird problem this week that took me hours to resolve. I had created a BindingSource so that I could set up DataBinding for controls on my form. Everything bound correctly and updated the DataTable.

...but everytime I called DataAdapter.Update on the DataTable it would complain that a particular foreign key field was null - even though I could see the value in the DataTable using the DataSet visualizer!

After simplifying my solution in a test project and adding to it incrementally to see what was causing the problem I stumbled across the answer.

I was doing this:
DataRow drow = myDataTable.NewRow();
myDataTable.Rows.Add(drow);

This approach has worked for me many times, hence the amount of time I spent finding this solution:

myBindingSource.AddNew();

So, it turns out, if you use a BindingSource you have to call it's methods for CRUD operations!

Weird, I'm sure this is a bug. I even checked the RowState using the old method which told me that I had added the row.

If anyone can explain this behaviour I'd be interested to hear it!

1 comment:

Anonymous said...

Good post.