Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView update datasource directly after changed Checkbox value

I have a System.Windows.Forms DataGridView that is bound to a List<MyObject>.
The class MyObject contains a boolean property that is bound to DataGridViewCheckboxCell within the DataGridView.

public class MyObject
{
    public decimal DefaultValue {get; set; }
    public bool HasCustomValue {get;set; }
    public decimal CustomValue {get;set; }
    public decimal CurrentValue
    {
        get
        {
            return HasCustomValue
                ? CustomValue
                : DefaultValue;
        }
}

If I change the value of HasCustomValue another (readonly) property CurrentValue changes it's value, too. That is done by implementing the INotifyPropertyChanged event (I left that part in the source example for simplicity)

If I changed HasCustomValue from outside the DataGridView, the column bound to CurrentValue gets updated immediately. Howevery, If the users enables/disables the checkbox, HasCustomValue is not changed in the underlying datasource unless he leaves the column by clicking with the mouse or pressing the TAB key.

Is there a way to force the grid to update the datasource directly after changing a checkbox value?

If I bind a Control Property I have the ability to set the DataSourceUpdateMode to Windows.Forms.DataSourceUpdateMode.OnPropertyChanged but I haven't found anything like that in a DataGridView

like image 329
Jürgen Steinblock Avatar asked Jan 03 '11 15:01

Jürgen Steinblock


2 Answers

I assume you are using bindingsource then on Check Box Click event/Edited do the ,

    BindingSource.EndEdit()
like image 54
indiPy Avatar answered Sep 30 '22 02:09

indiPy


I had a similar problem. And I wasn't using a BindingSource, just a BindingList. After lots of frustration and experimentation (and following different solutions that didn't quite work),

I simply did this:

  • override the DataGridView's CellMouseUp event
  • in the event, call the DataGridView's EndEdit() method.
like image 30
Rob Bryce Avatar answered Sep 30 '22 03:09

Rob Bryce