How to get values ​​from the last row in a DataTable?

I'm having trouble getting values ​​from the last inserted row in the data table. I have a login form and the values ​​will be inserted into the table with the identifier (int, auto increment value), userID (int), logintime (smalldatetime) and logouttime (smalldatetime). The code that is used inside the login button thus inserts all values ​​except the exit time

DateTime t1 = DateTime.Now; objbal2.insertLoginTime(s, t1); 

and in the exit button I update the table, so I need to get the latest row values. I am updating a table with a reference to the ID value and user ID. Can I use this query to get values? But I can not understand how?

 SELECT COLUMN FROM TABLE ORDER BY COLUMN DESC 

Thank you in advance

+6
source share
4 answers

if you need to read the values ​​from the last line, then

 DataRow lastRow = yourTable.Rows[yourTable.Rows.Count-1]; 

will return you the last line. and you can read the values ​​from it.

My second assumption is that by datatable you are referencing a table in sql server.

Then with a little modification, your request is also fine.

 SELECT TOP 1 COLUMN FROM TABLE ORDER BY COLUMN DESC 
+20
source
 var dt = new DataTable(); dt.AsEnumerable().Last(); 

dt.AsEnumerable() returns IEnumerable<DataRow>

+6
source

You can get the value from your session and then update your database according to your change

 DateTime t2 = DateTime.Now; DataRow Row = Mylagin_dataTable.Rows.Count-1 Row[0]["LogoutTime"] = t2 ; 

if your id is in session use below

 DateTime t2 = DateTime.Now; DataRow Row = Mylagin_dataTable.Select("LoginID='"+ HttpContext.Current.Session["loginID"] + "'"); Row[0]["LogoutTime"] = t2 ; 
+1
source

Run the following query on the Exit Exit event, this will do your job

string _query = string.Format("update top 1 SessionTable set LogOutTime = {0} where UserID = {1} order by ID desc", DateTime.Now, UserID);

0
source

Source: https://habr.com/ru/post/952815/


All Articles