ms access - Selected value to stay selected in Datagridview after updating in database c#? -
i have datagridview , getting of data database. did create method show data thing is, after calling method, scroll returns top dont want happen. created method purpose of showing newly added data , updating color.
private void showalldata() { try { using (oledbconnection conn = new oledbconnection(globalvar.connectionstring)) using (oledbdataadapter sda = new oledbdataadapter("select * tbltest", conn)) { datatable dt = new datatable(); sda.fill(dt); datagridview1.datasource = dt; (int x = 0; x < datagridview1.rowcount; x++) { if (datagridview1.rows[x].cells["color"].value == "green") datagridview1.rows[x].defaultcellstyle.backcolor = color.green; else datagridview1.rows[x].defaultcellstyle.backcolor = color.red; } } } catch (exception ex) { messagebox.show(ex.tostring(), "error", messageboxbuttons.ok, messageboxicon.error); } } private void btnadd_click(object sender, eventargs e) { try { using (oledbconnection conn = new oledbconnection(globalvar.connectionstring)) using (oledbcommand cmd = new oledbcommand("insert tbltest (color) values ('red')", conn)) { conn.open(); cmd.executenonquery(); } } catch (exception ex) { messagebox.show(ex.tostring(), "error", messageboxbuttons.ok, messageboxicon.error); } //update datagridview1 backcolor showalldata(); } private void btnupdate_click(object sender, eventargs e) { try { using (oledbconnection conn = new oledbconnection(globalvar.connectionstring)) using (oledbcommand cmd = new oledbcommand("update tbltest set color = 'green' id = " + datagridview1.selectedrows[0].cells[0].value, conn)) { conn.open(); cmd.executenonquery(); } } catch (exception ex) { messagebox.show(ex.tostring(), "error", messageboxbuttons.ok, messageboxicon.error); } //update datagridview1 backcolor showalldata(); }
use datagridview.firstdisplayedscrollingrowindex
property. sets index of row first row displayed on datagridview.
in case since changing datasource
, new rows might have been added. can't use selected row index. have identify row selected earlier (using unique identifier) , index , set above property index number.
instead of resetting datasource
, merge queried table existing table using datatable.merge
, refresh grid using datagridview.refresh
.
or can fill original datatable again.
datatable origtable = datagridview1.datasource datatable; sda.fill(origtable); datagridview1.refresh();
Comments
Post a Comment