Link to home
Start Free TrialLog in
Avatar of ayha1999
ayha1999

asked on

Insert and update

Hi,

I have one record in a table and two records in a gridview as follows.

Id (PK) Name  Points
1         abc        10

and in gridView control
Id  Name     Points
1   abc           20
2   xyz           30

I want to insert and update records from the gridview to the table. In this scenario, Id=1 is already exists in the table so I want to update it and Id=2 is not in the table so I want insert it. i.e. Two operations in one execution. How can I deal this scenario?

Please help me.

Thanks

ayha
Avatar of Jesus Rodriguez
Jesus Rodriguez
Flag of United States of America image

For each Rw as GridviewRow in Gridview1.rows
 ID=rw.cell(0).value
 dim qry as string="select id from table_name where id='" & ID & "'"
 dim t as new datatable
 dim adt as new sqldataadapter(Qry,YourSqlConn)
 t.clear()
 adt.fill(t)
 if t.rows.count>0 then
   'update
     qry="update table set name='" & rw.cell(1).value &"',Points='" & rw.cell(2).value &"' where ID='" & ID &"'"
 else
  'Insert
   qry="INSERT INTO TABLE(NAME,POINTS) VALUES('" & rw.cell(1).value &"','" & rw.cell(2).value &"')"
end
 dim k as new datatable
 dim adk as new sqldataadapter(Qry,YourSqlConn)
k.clear()
 adk.fill(k)
Next
ASKER CERTIFIED SOLUTION
Avatar of Jesus Rodriguez
Jesus Rodriguez
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ayha1999
ayha1999

ASKER

In the scenario here, insert and update should happen same time because id=1 is already in the table so need to update and id=2 is not there so need to insert. I think in the above code it either insert or update.

Thanks
Could you please give me a sample for the scenario I posted?

Thanks

ayha
Thanks