c# - Save changes from dataGridView to SQL Server DB -
i have form datagridview display content of table attendance
tagid sessionid scanningtime --------------------------------------- 4820427 test1 14/08/2013 18:12
i add record manually table this....
tagid sessionid scanningtime --------------------------------------- 4820000 test1 14/08/2013 18:12 0000001 test2 15/08/2012 17:00
...and save changes sql server database after button has been clicked.
i have tried creating update query:
command.text = "update attendance set tagid= @tagno, sessionid= @sessionno, scanningtime= @scantime";
but i'm not sure how assign values dgv parameters.
what correct way save changes datagridview sql server database?
please note not use dataset or tableadapter when working dgv.
you're going want consume rowsadded
method of datagridview
, cache necessary information insert
data:
// new form field caching private list<datagridviewrow> _addedrowscache = new list<datagridviewrow>(); private void datagridview1_rowsadded(object sender, datagridviewrowsaddedeventargs e) { (int = e.rowindex; < e.rowindex + e.rowcount; i++) { _addedrowscache.add(datagridview.rows[i]); } }
and when you're ready submit data database:
// new class field store insert sql private string _insertsql = "insert tbl (field1, field2) values (@field1, @field2)"; // block goes inside click event if (_addedrowscache.count > 0) { using (sqlconnection c = new sqlconnection(connstring)) { c.open(); foreach (datagridviewrow r in _addedrowscache) { using (sqlcommand cmd = new sqlcommand(sql, c)) { // add parameter values, don't know `val(n)` // comes here. maybe `databounditem` // off `datagridviewrow`, or maybe `cell` // out of `cells` collection of `datagridviewrow` cmd.parameters.addwithvalue("@field1", val1); cmd.parameters.addwithvalue("@field2", val2); cmd.executenonquery(); } } } }
Comments
Post a Comment