LastValue

Public Module DataTableExtensions
    <System.Diagnostics.DebuggerStepThrough()> _
    <System.Runtime.CompilerServices.Extension()> _
    Public Function LastValue(Of T)(ByVal dt As DataTable, ByVal ColumnName As String) As T
        Return dt.Rows.Item(dt.RowCount).Field(Of T)(dt.Columns(ColumnName))
    End Function
    <System.Diagnostics.DebuggerStepThrough()> _
    <System.Runtime.CompilerServices.Extension()> _
    Public Function LastValue(Of T)(ByVal dt As DataTable, ByVal ColumnIndex As Integer) As T
        Return dt.Rows.Item(dt.RowCount).Field(Of T)(dt.Columns(ColumnIndex))
    End Function
    <System.Diagnostics.DebuggerStepThrough()> _
    <System.Runtime.CompilerServices.Extension()> _
    Public Function RowCount(ByVal dt As DataTable) As Integer
        Return dt.Rows.Count - 1
    End Function
End Module
Example:
Public Class Form1
    Private Sub Demo()
        Dim dt As DataTable = GetData()
        Console.WriteLine(dt.LastValue(Of Int32)("ID"))
        Console.WriteLine(dt.LastValue(Of String)("Column2"))
    End Sub
    Private Function GetData() As DataTable
        Dim MockedData As New DataTable
        MockedData.Columns.AddRange(New DataColumn() _
            { _
                New DataColumn("ID", GetType(System.Int32)), _
                New DataColumn("Column1", GetType(System.String)), _
                New DataColumn("Column2", GetType(System.String)) _
            } _
        )

        MockedData.Rows.Add(New Object() {1, "A", "Apples"})
        MockedData.Rows.Add(New Object() {2, "B", "Grapes"})
        MockedData.Rows.Add(New Object() {3, "A", "Pears"})
        MockedData.Rows.Add(New Object() {4, "A", "Cherries"})
        MockedData.Rows.Add(New Object() {5, "B", "Oranges"})
        MockedData.Rows.Add(New Object() {6, "A", "Prunes"})
        MockedData.Rows.Add(New Object() {7, "A", "Grapes"})
        MockedData.Rows.Add(New Object() {8, "B", "Oranges"})
        MockedData.Rows.Add(New Object() {9, "B", "Oranges"})

        Return MockedData

    End Function
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Demo()
    End Sub
End Class

Description

Returns the the last row value for a column

Details

Double click on the code to select all.

 

;