I am searching for codes that could find the min and max(or first and last values) from a column in a datatable.

I have stored the datatable with four column values i want to find the min and max values from the third column(index 2) and display it to the user.
I tried many ways but all are causing exceptions...

Last i tried this code but even this is not working..

count = Convert.ToInt32(dt.Rows.Count);
  start = Convert.ToInt32(dt.Rows[0][2].ToString());
  end = Convert.ToInt32(dt.Rows[count][2].ToString());


i did try that but it is showing error in the 2nd row itself (line 3)...
unless the get the starting values what is the use of end values...

can u give some other type of code or method that u know..


Edited 5 Years Ago by vincezed: n/a

Oops, I guess the syntax got to be more something like dt.Rows[count-1,2]. instead of dt.Rows[count-1][2].

are u sure.. it is a datatable i think for datatable this is the syntax and what u have said is for a multidimensional array .. i guess so...

Sorry, my fault, the syntax you used is correct.
Must have been a bit too late in the evening for me :$

You can used following code

int min = dt.Rows[0][2]; // assuming you want the third column (index 2)
for(int i = 1; i < dt.Rows.Count; i++) 
    if(min > (int)dt.Rows[i][2]) min = (int)dt.Rows[i][2];

// maximum
int max = dt.Rows[0][2]; // assuming you want the third column (index 2)
for(int i = 1; i < dt.Rows.Count; i++) 
    if(max < (int)dt.Rows[i][2]) max = (int)dt.Rows[i][2];

Edited 5 Years Ago by __avd: Added [code] tags.

if you are using sql database.. you can just fire a simple query. like

select MIN(yourColumnName) from yourTableName;

select MAX(yourColumnName) from yourTableName;
The most evident is sometimes hard to find...

Your Question is not so clear, Consider Following DataTable:

DataTable dt = new DataTable();

dt.Rows.Add(2, "Hari");
dt.Rows.Add(1, "Sharad");
dt.Rows.Add(3, "Gopal");
dt.Rows.Add(6, "Suman");
dt.Rows.Add(5, "Rabi");

-If You want to get value of just first and last row, it is more simple. Code is like:
int firstRowIdValue = Convert.ToInt32(dt.Rows[0]["ID"]);
int lastRowIdValue = Convert.ToInt32(dt.Rows[dt.Rows.Count - 1]["ID"]);

- But If You Want MIN And Max Value. Code will be as:
int minVal =Convert.ToInt32(dt.Compute("min(ID)", string.Empty));
int MaxVal = Convert.ToInt32(dt.Compute("max(ID)", string.Empty));
MessageBox.Show("Min Value=" + minVal.ToString() + " AND Max Value" + MaxVal.ToString());

Thanks all for your reply. I found some other method to find the solution. I used a listview to display the value and from that i got the max and min i needed..

thanks any way..

This article has been dead for over six months. Start a new discussion instead.