daniel aagentah
daniel aagentah

Reputation: 1702

VB.net For Each Loop Not Accounting for First Datarow

I am currently looping through a data gridview in Visual Studio, The Loop works well and the code does pretty much what I want,

My only problem is that it seems to skip, or not account for the first row in my gridview, I have looked online to resolve this but cannot find anything,

I was wondering if i could get some assistance with this...

Here is my code for the loop:

            'Checks the flags for montor/expiry date to set red or green cells
        '------------------------------------------------------------------
        For Each Row As GridViewRow In GridView3.Rows
            '-----------------------------------------------------------------------------------------

            Dim MonitorVal As String = GridView3.DataKeys(e.Row.RowIndex).Values("Monitor").ToString
            If MonitorVal.Contains("Yes") Then

                Dim IsExtention As String = GridView3.DataKeys(e.Row.RowIndex).Values("FileName").ToString
                If IsExtention = "" Or IsExtention = Nothing Or IsExtention = "Null" Then
                    'set red
                    '--------
                    e.Row.BackColor = Drawing.Color.LightPink
                Else
                    'else green
                    '-----------
                    e.Row.BackColor = Drawing.Color.LightGreen
                End If

            Else
                'else green
                '-----------
                e.Row.BackColor = Drawing.Color.LightGreen
            End If
        Next

Upvotes: 0

Views: 575

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460148

I guess that "first row in gridview" actually means the header-row of the grid. That is not returned from GridView.Rows, only rows with DataControlRowType.DataRow are returned. You can get it only in events like RowDataBound or RowCreated. I would suggest to use RowDataBound in this case:

Protected Sub GridView3_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView3.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.Header
            ' ... '
        Case DataControlRowType.DataRow
            ' ... '
        Case DataControlRowType.Footer
            ' ... '
    End Select
End Sub

Documentation:

Only rows with their RowType property set to DataControlRowType.DataRow are stored in the Rows collection. The GridViewRow objects that represent the header, footer, and pager rows are not included in the collection.

Upvotes: 1

Related Questions