Search code examples
vb.netwinformsdevexpress

MAX & MIN Value on GridView Column VB.NET


I am developing a small program to get the maximum of a specific column in a gridview (DevExpress), but I could not execute it as I wanted.

Can you support me in seeing where I have the error?

    Dim cells() As GridCell = GridView2.GetSelectedCells()
    Dim values As New List(Of Decimal)()
    For i As Integer = 0 To GridView2.RowCount - 1
        Dim value As Decimal = Convert.ToDecimal(GridView2.GetRowCellValue(cells(i).RowHandle, cells(i).Column))
        values.Add(value)
    Next i
    values.Sort()

    MsgBox(values.Max().ToString())

Regards.


Solution

  • With the built in DataGridView, the number of rows can be Rows.Count -2 because there is an extra row for the user to enter a new record. I have no idea if DevExpress works that way but it is worth a try.

    For i As Integer = 0 To GridView2.RowCount - 2
    

    If your GridView uses a DataTable as a DataSource, then the following code might help. If the DataTable is still available then just start with that. Otherwise extract it from the grid.

    DataTable does not implement IEnumerable but there is an extension method to get the interface (.AsEnumerable).

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DirectCast(DataGridView1.DataSource, DataTable)
        Dim maxValue = Aggregate r In dt.AsEnumerable
                       Into MaxID = Max(r("ID"))   '"ID" is the name of a column
        MessageBox.Show(maxValue.ToString)
    End Sub
    

    Same thing for Min just change Max to Min.