Recent projects require real-time editing of Datagirdview controls in Winfrom to ensure real-time synchronization with database data.
Requirements: Edit and add the Datagirdview to ensure the data is synchronized with the database.
Analysis: This is to operate on an event, at the time of completion is to add or modify the operation, the judge is to add or modify the ID can be judged, if the database exists the same ID, then edit, does not exist to add, operation is clear, is the choice of events, DataGridView events, I chose the Cellendedit event (which occurs when the editing mode of the currently selected cell is stopped), there are many events, and different events are selected for different situations.
//determining the coordinates of rows and columns intRowIndex =E.rowindex; intColindex =E.columnindex; if(RowIndex <0|| Colindex <0)return; //value Operation stringID = This. Gvperson.rows[rowindex]. cells[0]. Value.tostring (); stringsql =@"SELECT * from person where id= '"+ ID +"'"; DataTable DT= dbhelper.executetable (sql, CommandType.Text,NULL); if(dt. Rows.Count >0) { //To perform a modification operation } Else { //To perform an add operation} DoWork ();
View Code
Do here, actually completed the real-time editing, add, but this is far from enough, the data is updated, added to the database, then how to refresh Datagirdview it?
Public Delegate voidMyinvoke (); Public voidDoWork () {Myinvoke mi=NewMyinvoke (LoadData); This. BeginInvoke (MI); } Public voidLoadData () {stringsql =@"SELECT * from person"; DataTable DT= dbhelper.executetable (sql, CommandType.Text,NULL); This. Gvperson.datasource =DT; }
If the same as usual, reload once, such a refresh can not, instead, will be error, with the way of delegation to be resolved.
When doing DataGridView operation, will encounter dataerror error, only need to open this event can be.
C#datagridview Edit, add line