i have my first aspx page that has data thatthe user fills in. it is in format of textbox's and at the end of it all the user clicks submit and all data goes in the database. In the database each record gets an ID field. Now when the users clicks submit and goes to the next page, i want the ID's (they could be 1 to 1000+) from the DB that he just inserted and have them available on the second page. how can i take all the id's from page 1 to page 2? can i do it in session? or something else. Please put some sample code so i can understand better.
A:
It can be done, and it's not so hard. In a nutshell, here's what you will want to do:
- for each item you insert into the database, return the newly created item's id
- store the saved item's id in your database methods someplace easy to access - Session is a good place.
- on the next page, you can access your Session variable to retrieve the id's you saved.
(Currently editing post to add code)
The best and safest way to return newly inserted ID's is through transactions (plus, if there is a problem with the insert, you can roll it back). Here's how a transaction would look where we do an insert and return an ID:
ALTER PROCEDURE [dbo].[storeFrontItems]
@itemName NVARCHAR(255),
@itemDescription NVARCHAR(255),
@newItemID INT OUTPUT
AS
BEGIN TRANSACTION
INSERT INTO storeFrontItems (Name, Description) VALUES (@itemName, @itemDescription)
SET @error = @@ERROR
IF @error <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN @error
END
ELSE
BEGIN
SELECT @newItemID = @@IDENTITY
END
COMMIT TRANSACTION
RETURN
Then you can store your new ID in a session variable
Dim newlyCreatedItemID int
newlyCreatedItemID = databaseInsertNewItem /* ... */
/* to store it in a session variable */
Session("NewItemID") = newlyCreatedItemID
/* to retrieve it from a session variable */
newlyCreatedItemID = i = CType(Session("NewItemID"), newlyCreatedItemID )
rlb.usa
2010-06-17 20:51:14
i get this part. so when i come back with the @newitemid, then i do Session("itemid") = @newitemid. wont it overwrite the first newitemid with the next one on each insert? how can i put them in session as say 1,2,3,4,5... or am i understanding wrong?
poller
2010-06-17 21:02:42
You can store _objects_ in Session too - like, arrays, hashmaps, etc. Will that help you?
rlb.usa
2010-06-17 21:04:46
A:
First create some sort of sessionId and store it in the session object.
Session["SessionId"] = Guid.NewGuid().ToString();
When storing the id's, in the db, also record the SessionId(above) with it, so you'll know all the records for that session.
Then in the next page, just do a query to get all id's related to that SessionId
Ed B
2010-06-17 20:52:17