Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commit current dirty cell on clicking save button from any datagridview on form

I have a form with multiple datagridviews. On save the entire dataset will be serialized to a strongly typed property bound to a sql varbinary(max) Works fine.

Of course the current "dirty" cell will not be saved as mentioned here :

DataGridView -Value does not gets saved if selection is not lost from a cell

My problem is the user could be coming from any one of 20 datagridviews when they click SAVE.

Is there any way, short of checking for a dirty cell in each datagridview to commit any dirty cell before the save ( clicking another textbox control before the save does the trick but calling the focus() of that textbox prior to the save does not )

I was thinking perhaps catching the event of leaving the grid but it seems the base problem is clicking a button (for reasons I think I understand) does not fire lostfocus events for the current control and it doesn't seem the click handler args knows what the last current selected control is.

Guidance appreciated.

TIA

like image 232
Charles Hankey Avatar asked Dec 03 '25 05:12

Charles Hankey


1 Answers

Hook up all your datagridviews to the same Leave event handler. The leave event is processed before the click event. Inside your leave event, capture the datagridview that just lost focus. When the save button is clicked, check if the last datagrid view that was left has any unsaved data...

Example:

    DataGridView _lastDataGridView = null;
    private void dataGridView_Leave(object sender, EventArgs e)
    {
        _lastDataGridView = sender as DataGridView;
    }

    private void saveButton_Click(object sender, EventArgs e)
    {
        if (_lastDataGridView != null)
        {
            // check if data needs saving...
        }
    }

Edit 1: As for you not receiving the leave event before the click event, I'm not seeing that behavior. To reproduce what I've done, create a form with a DataGridView and a button. Add two text box columns to the DataGridView, hook up the events as described and see if the _lastDataGridView member is set when executing sendButton_Click. It is on my end.

Edit 2: After trying my datagridview I noticed that the data was always being saved. So I suspected you had some different settings. I turned on "VirtualMode." This causes the same behavior that you're describing. If possible, try turning VirtualMode off and see if the data gets saved to the DataGridView as expected. Otherwise try implementing the suggestions outlined in this MSDN article.

like image 79
Jason D Avatar answered Dec 04 '25 18:12

Jason D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!