Help me to update my datagridview

praveen242424

Member
Joined
Sep 30, 2013
Messages
7
Location
Coimbatore, Tamil Nadu, India
Programming Experience
Beginner
Hi I am using vb.net to design my application and sql sever ce for database connection. In this i am using a form to insert the data into database and a datagridview for viewing and editing the data stored.

My problem is when I insert a new data in my form, it was not updated on the datagridview. But once I close the application and restart the data is updated on the datagridview. Please help me to update my database without restarting my app.

THANKS IN ADVANCE.
 
I can't believe the number of people who make this same mistake. You're doing it backwards. There's no way that your grid should not be showing the new data if it's in the database because it should be showing in the grid first. If it's not showing in the grid then there shouldn't be anything to save to the database.

1. Call Fill on a data adapter or table adapter to populate a DataTable with data from the database.

2. Bind the DataTable to your DataGridView via a BindingSource.

3. Perform all your edits (inserts, updates and deletes) on the data in the DataGridView/DataTable. The user makes their edits via the grid and and changes made in code are done via the BindingSource. Because all three (DataTable, BindingSource and DataGridView) are bound, a change made in any one will automatically be reflected in the other two.

3a. To insert a new record, call AddNew on the BindingSource, set the fields of the DataRowView that it returns and call EndEdit on the BindingSource to commit it to the DataTable. Note that, in this and most situations, a DataRowView can be used in the same way as a DataRow.

3b. To edit the row currently selected in the DataGridView, get the corresponding DataRowView from the Current property of the BindingSource and set its fields. To edit other than the selected row, index the BindingSource itself to get a DataRowView and proceed as before. Note that the row indexes in the BindingSource and DataGridView match while they may differ to those in the DataTable. You don't need to touch the DataTable anyway so that's no issue.

3c. To delete the selected row, call RemoveCurrent on the BindingSource. To deleted other than the selected row, call Remove on the BindingSource and provide the row index.

4. When you're done editing the data, call Update on the same data adapter or table adapter to update the database with all the changes from the DataTable.

That's it, that's all. DO NOT call ExecuteNonQuery to modify the database directly without going via the DataTable.
 
Back
Top