3
votes

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

2

2 Answers

1
votes

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.

0
votes

Why not use the DataGridView's CellEndEdit event to mark a boolean flag that the DGV is dirty? Assuming you are using SQL, you would create an UpdateCommand, SelectCommand, and DeleteCommand for each DGV. When you want to "save" the changes, just call DataAdapter.Update(myDataSet, "TABLE NAME"); for the DataAdapter associated with your DataGridView. I use this technique now for one DGV and it works fine.