I’m using a winform DataGridView for data entry. The problem is that when my user has entered a row but not clicked off it, that row isn’t getting saved to the grid’s datasource (a datatable in memory). So, when my user submits the form, I want to detect if the DataGridview has focus, and simulate a keypress (tab?) or set the focus to a different control or do some other operation to save the current row without changing the data.
DataGridView.ContainsFocus is always returning false, as is DataGridView.Focused. Is there another property i should be using? How should I save this row of data?
EDIT: See this question Trouble using DataGridViewComboboxColumn for input for how I’m creating the DataTable and binding it to the datagridview. And datagridview not allowing user to delete row to see another issue I had with this same datagrid.
Windows forms controls can be connected directly to data sources, but are designed to be used with a BindingSource control. This is used to marshall input from form controls to and from a data source.
It is a component which you can drag onto your form in the designer, and then you can set it as the data source for your datagridview control.
Once it is on the form, you can use the designer to set it as the datasource for your datagridview. Then you can use an event handler, for example, the form load event handler to provide a datatable as the data source for the binding source.
The binding source provides you with much finer control over how and when data is transferred from the form controls to the underlying data sources. Simply using the Binding Source may fix your problem. If not, then calling the EndEdit method on the binding source before attempting to save the data should cause any outstanding edits to be written to the datatable.
For a simple example, create a new Windows forms project. To the form, add a datagridview called “datagridview1”, a BindingSource with the name peopleBinding source, and a command button called saveButton. Set the datasource for gridview1 to be peopleBindingSource.
Add event handlers for form.Load and saveButton.Click as follows:
Run the application, and you should find that if you inspect the data table in SaveButton_Click that any changes you have made to the data are persisted.
If you prefer Visual Studio to write all the code for you:
Visual studio will add the necessary DataGridView, BindingSource, etc and wire them all up for you. You can then inspect the code to see how it all fits together.