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

Capturing the value of a databound DataGridViewCheckBoxCell

I had a DataGridViewCheckBoxColumn in my DataGridView that was bound to a BindingSource. I wanted to capture the value of the CheckBoxCell when a user checked or unchecked the cell. So I set the TrueValue and FalseValue for the cell and used the

satelliteScenesDataGridView["inCartDataGridViewCheckBoxColumn", e.RowIndex].Value

But this was always returning false even if the checkbox was checked. After scouring the web I found that you have to use

satelliteScenesDataGridView["inCartDataGridViewCheckBoxColumn", e.RowIndex].EditedFormattedValue

this returns the formatted value of the cell even if the value has not been commited.