C# 如何从数据表的最后一行检索值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18528736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve values from the last row in a DataTable?
提问by Cindrella
I am having problems retrieving values from the last inserted row in a Data-table. I have a login form and the values will be inserted in the table has the ID (int,an auto incremented value), userID (int), logintime (smalldatetime) and logouttime(smalldatetime). The code which is used to inside the login button,it thus inserts all values except the log out time
我在从数据表中最后插入的行中检索值时遇到问题。我有一个登录表单,将插入表中的值具有 ID(int,自动递增值)、userID(int)、logintime(smalldatetime)和 logouttime(smalldatetime)。用于登录按钮内部的代码,因此插入除注销时间以外的所有值
DateTime t1 = DateTime.Now;
objbal2.insertLoginTime(s, t1);
and in the log out button I am updating the table, so I have to retrieve the last row values. I am updating the table with reference to the ID value and userID. Can I use this query get the values? But I can't figure out how?
在注销按钮中,我正在更新表,因此我必须检索最后一行的值。我正在参考 ID 值和用户 ID 更新表。我可以使用此查询获取值吗?但我想不通怎么办?
SELECT COLUMN FROM TABLE ORDER BY COLUMN DESC
Thanks in advance
提前致谢
采纳答案by Ehsan
if you have to read the values from last row then
如果您必须读取最后一行的值,则
DataRow lastRow = yourTable.Rows[yourTable.Rows.Count-1];
will return you last row. and you can read the values from it.
将返回您的最后一行。你可以从中读取值。
My second guess is that by datatable you are referring to table in sql server.
我的第二个猜测是,通过数据表,您指的是 sql server 中的表。
Then with small modification your query is fine as well.
然后通过小的修改,您的查询也很好。
SELECT TOP 1 COLUMN FROM TABLE ORDER BY COLUMN DESC
回答by Sruti
var dt = new DataTable();
dt.AsEnumerable().Last();
dt.AsEnumerable()
returns an IEnumerable<DataRow>
dt.AsEnumerable()
返回一个 IEnumerable<DataRow>
回答by Ankush Madankar
Execute following query on Application Exit event, this will do your work
对应用程序退出事件执行以下查询,这将完成您的工作
string _query = string.Format("update top 1 SessionTable set LogOutTime = {0} where UserID = {1} order by ID desc", DateTime.Now, UserID);
string _query = string.Format("update top 1 SessionTable set LogOutTime = {0} where UserID = {1} order by ID desc", DateTime.Now, UserID);
回答by MSTdev
You can got the value from your session and then update your database as per your change
您可以从会话中获取值,然后根据您的更改更新数据库
DateTime t2 = DateTime.Now;
DataRow Row = Mylagin_dataTable.Rows.Count-1
Row[0]["LogoutTime"] = t2 ;
if your ID in sessionthen use below
如果您在会话中的ID 则在下面使用
DateTime t2 = DateTime.Now;
DataRow Row = Mylagin_dataTable.Select("LoginID='"+ HttpContext.Current.Session["loginID"] + "'");
Row[0]["LogoutTime"] = t2 ;