c# - Save edits from dataGridView to SQL Server database (no DataSet or TableAdapter) -
i have form datagridview display content of table attendance
tagid sessionid scanningtime --------------------------------------- 4820427 test1 14/08/2013 18:12
user able alter existing records or add new ones.
an example of attendance table after editing data:
tagid sessionid scanningtime --------------------------------------- 4820000 test1 14/08/2013 18:12 0000001 test2 15/08/2012 17:00
i user able save changes dgv sql server after button clicked, not sure how achieve this. please note not use dataset or tableadapter when working dgv.
my code:
private void updatebtn_click(object sender, eventargs e) { foreach (var row in datagridview1.rows) { string connstr = "data source=duzy;initial catalog=autoregsql;integrated security=true"; sqlconnection myconn = new sqlconnection(connstr); myconn.open(); string query = @"update attendance" + " set tagid= @tagno, sessionid= @sessionno, scanningtime= @scantime "; sqlcommand command = new sqlcommand(query, myconn); command.parameters.add("tagno", sqldbtype.int).value = //how value row.tagid column? command.parameters.add("sessionno", sqldbtype.char).value = //how value row.sessionid column? command.parameters.add("scantime", sqldbtype.datetime2).value = //how value row.scanningtime column? sqldataadapter adapter = new sqldataadapter(command); adapter.fill(queryresult); roomactivesessionform.dgvsetdatasouce(queryresult); myconn.close(); } }
use row.cells[int index].value or row.cells[string columnname].value. see http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.cells.aspx
foreach (datagridviewrow row in this.datagridview1.rows) { int tagid = convert.toint32(row.cells["tagid"].value); }
Comments
Post a Comment