Click here to Skip to main content
15,916,189 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to get the last cell's id of a column in a data table
Posted
Updated 12-Mar-15 18:36pm
v2
Comments
King Fisher 13-Mar-15 0:50am    
what do you mean "last cell's id of a column" ?
vinu paul 13-Mar-15 1:04am    
example :
ID UserId Password
----------------------
1 vvv v
2 asd a
3 dsa r
4 sdasd r

i want the last id(that is '4')..how can i get it ??
King Fisher 13-Mar-15 1:12am    
have a look on my Answer.
Maciej Los 13-Mar-15 3:02am    
Do you want last row or last (max) id? It makes difference! The order of data in DataTable depends on many factors. So, the last row does not need to be the max id!
King Fisher 13-Mar-15 3:06am    
You are right.

Please, read my comment to the question and have a look at below sample (using Linq[^]):

XML
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add(dc);
dc = new DataColumn("UserId", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Password", System.Type.GetType("System.String"));
dt.Columns.Add(dc);

dt.Rows.Add(new Object[]{1, "vvv", "v"});
dt.Rows.Add(new Object[]{2, "asd", "a"});
//max id
dt.Rows.Add(new Object[]{4, "sdasd", "r"});
//last row ;)
dt.Rows.Add(new Object[]{3, "dsa", "r"});


int lastid = dt.AsEnumerable().Select(x=>x.Field<int>("Id")).Last();
//returns 3

int maxid = dt.AsEnumerable().Max(x=>x.Field<int>("Id"));
//returns 4


As you can see, last row does not mean Max(ID).
Depending on what you want to achieve, change the code to your needs ;)
 
Share this answer
 
v2
Comments
vinu paul 13-Mar-15 3:45am    
thanks :)
Maciej Los 13-Mar-15 5:10am    
You're very welcome ;)
C#
var a = dt.Rows[dt.Rows.Count - 1];


To get last row data From DataTable.
 
Share this answer
 
v2
Comments
vinu paul 13-Mar-15 2:08am    
still i got the first row id
King Fisher 13-Mar-15 2:09am    
No way I have tested that.
King Fisher 13-Mar-15 2:10am    
Show your Code .What you have?
Maciej Los 13-Mar-15 3:03am    
King Fisher, please see my comment to the question.

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