Results 1 to 4 of 4

Thread: Getting max value of a column in a datatable?

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2003
    Posts
    47

    Getting max value of a column in a datatable?

    Hi. I would like to know how do i obtain the maximum value of all the records in a datatable of a particular column?

    For example:

    Code:
    Dim da As New SqlDataAdapter 
    Dim dtStudents As New DataTable 
    
    da.SelectCommand = New SqlCommand("SELECT StudentID, Name FROM Students", myConnection) 
    da.Fill(dtStudents)
    So now i have all my students record in the dtStudents datatable. How do i determine the maximum value of the StudentID?

    Thanks in advance,
    Archaven

  2. #2
    Frenzied Member
    Join Date
    Oct 2002
    Location
    Gammapolis
    Posts
    1,474
    If you need to get it after you fill your dataset you may fetch the data orderd by StudentID descending, then read the value of first row. Also you may select the maximum from database. "Select Max(StudentID), ..."
    'Heading for the automatic overload'
    Marillion, Brave, The Great Escape, 1994

    'How will WE stand the FIRE TOMORROW?'
    Eloy, Silent Cries and Mighty Echoes, The Vision - Burning, 1979

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2003
    Posts
    47
    Thanks lunatic. However, i've found a better way!. Thought of sharing with everyone.

    Code:
    Dim da As New SqlDataAdapter
    Dim dt As New DataTable
    Dim objValue As Object
    
    da.SelectCommand = New SqlCommand("SELECT StudentID, Name FROM Students", myConnection)
    da.Fill(dt)
    objValue = dt.Compute("Max(ID)", "")
    Cheers,
    Archaven

  4. #4
    Frenzied Member
    Join Date
    Oct 2002
    Location
    Gammapolis
    Posts
    1,474
    Thats good, but it is in the expense of one computing that can be avoided if you feel you need to sort data by StudentID, so you do all in one trip to database.
    'Heading for the automatic overload'
    Marillion, Brave, The Great Escape, 1994

    'How will WE stand the FIRE TOMORROW?'
    Eloy, Silent Cries and Mighty Echoes, The Vision - Burning, 1979

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width