Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey everyone,

I am inserting into a db table from codebehind.How can i get the ID of this last raw inserted from codebehind?...

Thanks
Amit
Posted
Comments
Rajesh Anuhya 29-Oct-10 6:37am    
Your Question is not clear for me.., if your inserting the ID field to a Table, you should know the ID value before inserting.....
Steven J Jowett 29-Oct-10 6:39am    
What DB are you using e.g. Access, SQL Server? Is the Id field sequencial? If so SELECT MAX(Id) FROM Table but has room for error.
AmitChoudhary10 29-Oct-10 6:40am    
Id in db table is self generated by identity-specification.And i am inserting into this table from code behind.....
AmitChoudhary10 29-Oct-10 6:41am    
SQL server 2005

The table will have two column called ID and Name
ID is auto generator
then use the below command for getting the last inserted record id


insert into tables('Arun');
select scope_identity();
 
Share this answer
 
Comments
AmitChoudhary10 29-Oct-10 6:42am    
thats for sql,i want to get id from codebehind,asp.net...
Steven J Jowett 29-Oct-10 6:47am    
The answer is valid. In your codebehind you will need to execute the insert and select statements as 1 transacrion. You could write a stored procedure to accept the values to insert and return the id
AmitChoudhary10 29-Oct-10 6:55am    
thanks man,gotcha..
Sqlcommand cmd=new SqlCommand("insert into dep(date)values ('10/11/2010');select scope_identity();",con);

string serviceID
= cmd.ExecuteScalar();
Label.Text=serviceID ;
 
Share this answer
 
v2
It could be easier if you use Data Access Application Block.

http://www.codeproject.com/KB/architecture/MS-EntLib-DataAccess1.aspx?msg=3168720 [^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900