Click here to Skip to main content
15,068,678 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
hello, I'm new to c# and I'm working on an application with a ADO .NET entity data model. How can I retrieve the last recorded id of a table, and show it value in a label?
Posted
Updated 22-May-13 0:52am
v3

If you want to get the last ID of an identity field in SQL you can use SCOPE_IDENTITY()

For example:
SQL
INSERT INTO table1(field1)
VALUES ('test')

SELECT SCOPE_IDENTITY() AS NewestID


If you want to do this later on, not when inserting a record you would just find the max ID
SQL
SELECT MAX(ID)  AS LastID
FROM table1
   
Comments
Nnorss 9-May-13 15:37pm
   
thanks! i just want to show the last id of the table in a label, how can i do that?
ZurdoDev 9-May-13 15:38pm
   
Run the SQL, select MAX(ID), etc and then put the result into a label. Do you have a database helper class? If not, use SqlCommand and SqlConnection.
ZurdoDev 9-May-13 15:45pm
   
Ado.Net is SQL so I am confused as to what you are doing. It sounds like you need to go through some tutorials and get up to speed on it.
ZurdoDev 9-May-13 16:01pm
   
You need to run that query somehow. Whatever method you want.
you r right ryanb31,
But, if ur table don't have Identity column then go for this...

SQL
create Procedure Get_LastRow
(@Tname Varchar(50))
AS
BEGIN
EXECUTE ('DECLARE GETLAST CURSOR DYNAMIC FOR SELECT ImageName FROM ' + @Tname)
OPEN GETLAST
FETCH LAST FROM GETLAST
CLOSE GETLAST
DEALLOCATE GETLAST
END


Then execute,
SQL
EXEC Get_LastRow 'dbo.Images'
   
C#
using (DbEntities db = new DbEntities())
        {

   int IdA = db.Table.Max(a => a.IdTable);
   label1.Text = IdA.ToString();
         }
   

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