The data in the datatable can be modified and updated to the database at the same time, which is convenient. The following is the implementation code:
Datatable table = new datatable (); // initialize a datatable object string sqlconnectionstring = "Data Source = computername-PC; initial catalog = charge_sys; user id = sa; Pwd = 123456; "; sqlconnection = new sqlconnection (sqlconnectionstring); // connect to the database sqlcommand = new sqlcommand (" select * From testb ", sqlconnection); sqldataadapter sqladap = new sqldataadapter (sqlcommand ); sqlcommandbuilder sqlbuilder = new sqlcommandbuilder (sqladap); // This sentence is very important, as if it was used for batch update // dataset dtst = new dataset (); dataset can also be used for completion, the corresponding implementation code sqlconnection is as follows. open (); sqladap. fill (table); // table = dtst. tables ["testb"]; datarow DR = table. rows [0]; // The first line // dr. beginedit (); // dr. endedit (); it seems that the two statements are mainly used for (INT I = 0; I <table. rows. count; I ++) // modify the content of each row in the table {DR = table. rows [I]; Dr ["F"] = 3; // The field name is f} // a primary key must exist in the testb table, otherwise, it is very important that you cannot update/******* sqladap. update (table); // sqladap. update (dtst, "testb"); sqlconnection. close (); MessageBox. show ("AA ");
The following is the able bound to the datagridview control. When the data in the datagridview dview changes, update the database code:
Datatable and datagridview control binding code:
Private void form1_load (Object sender, eventargs e) {string sqlconnectionstring = "Data Source = computername-PC; initial catalog = charge_sys; user id = sa; Pwd = 123456 ;"; sqlconnection = new sqlconnection (sqlconnectionstring); // initialize sqlconnection datatable table = new datatable (); sqldataadapter sqladap = new sqldataadapter ("select * From testb", sqlconnection); sqlconnection. open (); sqladap. fill (table); sqlconnection. close (); // display the data in Table testb in the dview this. datagridview1.datasource = table ;}
Update the changes in the datagridview to the database code:
Private void butupdate_click (Object sender, eventargs e) {datatable table = new datatable (); table = (datatable) This. datagridview1.datasource; string sqlconnectionstring = "Data Source = wanghaitao-PC; initial catalog = charge_sys; user id = sa; Pwd = 123456;"; sqlconnection = new sqlconnection (sqlconnectionstring ); sqlcommand = new sqlcommand ("select * From testb", sqlconnection); sqldataadapter sqladap = new sqldataadapter (sqlcommand); sqlcommandbuilder sqlbuilder = new sqlcommandbuilder (sqladap); // sqlconnection is required. open (); sqladap. fill (table); // a primary key must exist in the testb table; otherwise, sqladap cannot be updated. update (table); sqlconnection. close (); MessageBox. show ("AA ");}