简体   繁体   中英

How to use a c# datagridview to update a database file just like Access does?

I have googled everywhere and I am finally giving up and asking here.

I am working in Visual Studio 2010 with C#. I have set up a form with a datagridview connected to a MSSQL database and I need to save changes made in the datagridview back to the physical database. I am having some success but I think that I am going about some of it completely wrong because I can not get it to save consistently.

What I really want is for the updates to work just like they do when working with Access. When I edit a row in the datagridview and then leave that row, either by selecting another row or by selecting some other control on the form or even by changing to another form or quitting the application the row should be automatically pdated to the physical database.

The first part of this question I think is, what is the proper event to use to trigger the save and then second what methods should be used to actually write the data to the database?

there are a lot of events that could be used including

Leave Event which Occurs when the input focus leaves the DataGridView

CellLeave Event which Occurs when a cell loses input focus and is no longer the current cell

RowLeave Event which Occurs when a row loses input focus and is no longer the current row

MSDN has info on each of the DataGridView Events

In the Event you use, you would place your code to perform the UPDATE . There are lots of answers on SO about updating the database:

WinForms DataGridView - update database

C# WinForms - how to send updates from DataGridView to DataBase

My suggestion would be try try some of this code and then if you have problems, post another question with your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM