I have to insert records from the textboxes into a database using a SAVE button. Then using a id I'l be retrieving the data when clicking a retrieve button. Then I'l be modifying the records and update it into the database using the same SAVE button. The problem for me is using the same SAVE button for both inserting and updating.
How to insert and update records into access database using a single save button in asp.net with c#?
conditional logic based on id
if exists id then
update
else
assign id
insert
Reply:Assuming that your table is MyTable( MyId, MyField1, MyField2 ) here is a solution through defining a Stored Procedure which has the structure to be shown later.
Whenever the button Save is clicked, all you have to do is call the procedure SaveMyTable.
If you are inserting a record, set the parameter @prmId of the procedure to 0.
If you are updating a record, set the parameter @prmId to the value of the record's Id you want to update.
Code of the Stored Procedure:
CREATE PROCEDURE SaveMyTable
(
@prmId int,
@prmField1 varchar(100), -- assuming MyField1 is of type varchar(100),
@prmField2 smalldatetime -- assume MyField2 is of type smalldatetime
)
AS
IF (@prmId = 0)
-- Insert new record to Table
INSERT INTO MyTable (MyField1, MyField2) VALUES ( @prmField1, @prmField2) -- assuming MyId is an Identity
ELSE
-- update an existing record
UPDATE MyTable
SET
MyField1 = @prmField1,
MyField2 = @prmField2
WHERE
MyId = @prmId
Hope this helps.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment