Tuesday, September 21, 2010

CurrencyManager exception when repopulating datatable bound to a datagridview

Another gotcha..

I have a datagridview which is bound to a bindinglist which inturn is pointed to a datatable. Everything works fine until I clear the datatable and repopoulate the table. Then I start seeing the IndexOutOfRange and CurrencyManager exceptions. The gridview also tries to add more rows than what are in the datatable - wierd!!

Every time I had repopulated the datatable I was rebinding my bindinglist agian to the datatable - turns out this was the culprit - although I haven't figured out why!! So I got rid of these error by pointing the bindingsource to the datatable only once - on the OnLoad() event.


private void DataGrid_Load(object sender, EventArgs e)
{
bindingSource1.DataSource = dataset;
bindingSource1.DataMember = "tablename";
}
//and when I need to refresh the grid:
bindingSource1.ResetBindings(false);
ResetBindings just refreshes the binding source and reads the new values form the datatable. The lone parameter will be true only if the schema of the source has changed, in my case it hasn't

1 comment: