c# - How to populate database table from a gridview? -
my question depends upon need populate table in database, gridview. i've populated gridview datatable viewstate. can me?
string str = configurationmanager.connectionstrings["constr"].connectionstring; sqlconnection con = new sqlconnection(str); con.open(); sqlcommand cmd = new sqlcommand("select top 1 * bookings", con); sqldatareader reader = cmd.executereader(); if(reader.read()) { bookingid = convert.toint32(reader["id"]); } booking_tax(bookingid);//here have multiple entries taxes same bookingid
ok, here go: in code behind foreach loop on grid view rows, this:
foreach (gridviewrow rw in gridview1.rows) { var o = new object //in case booking object { id = convert.toint32(gridview1.datakeys[rw.rowindex].value), field1 = rw.cells[1].text.tostring(), field2 = convert.toint32(rw.cells[2].text.tostring()) } using (var context = new yourentities()) { //here save new row in database context.testdetail.add(o); context.savechanges(); } }
or normal insert sql statement:
foreach (gridviewrow row in gridview1.rows) { con.open(); sqlcommand cmd1 = new sqlcommand("insert bookings (id, labid, srno, test_id) values (@id1,@lab_id,@serialno,@testid)", con); cmd1.parameters.addwithvalue("@id1", orderid); cmd1.parameters.addwithvalue("@lab_id", row.cells[1].text); cmd1.parameters.addwithvalue("@serialno", row.cells[2].text); cmd1.parameters.addwithvalue("@testid", row.cells[3].text); cmd1.executenonquery(); }
i wrote code on fly. need ofcourse make cleaner , takecare of closing connection , disposing objects
if helps. mark answer :)!! cheers!!
Comments
Post a Comment