Zogglet
Zogglet

Reputation: 39

Handling RowDataBound causes dynamically-bound GridView to show only first record

I have a GridView control which I am dynamically binding to a DataTable which is populated by a query built based on a set of selected options.

What I am trying to do is simply handle the RowDataBound event in order to format specific rows based on the value of a database field. The code in this event handler works fine. My problem is, calling this event causes the GridView to only display the first record in the DataTable, almost as if the Gridview stops after binding to the DataTable after the first row is bound.

I have attempted adding the handler dynamically, but I get the same results.

Any ideas as to why simply handling this event causes the Gridview to do this?

I know for a fact that there is sufficient data being returned (the DataTable fills with all of the records, and the GridView shows all the records fine when not touching the RowDataBound event).

I'm adding the handler immediately after generating the query, filling the DataTable, and binding the GridView:

oDA.Fill(oDTbl)
figs_gv.DataSource = oDTbl
figs_gv.DataBind()
AddHandler figs_gv.RowDataBound, AddressOf gvRowDataBound 

The handler itself:

Protected Sub gvRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.DataRow Then
        If (e.Row.DataItem("Have") = "Yes") Then
            For i As Integer = 1 To e.Row.Cells.Count
                e.Row.Cells(i).BackColor = Drawing.ColorTranslator.FromHtml("#d3f1c7")
            Next
        End If
    End If

End Sub

I have also determined that, when handling RowDataBound, the GridView's DATABOUND event never gets fired; it seems to stop binding right after binding the first row.

Upvotes: 1

Views: 4423

Answers (1)

Zogglet
Zogglet

Reputation: 39

I have resolved my problem.

When stepping through my code, I discovered that I had been getting an "Index out of range" error when looping through the cells of each row as such:

For i As Integer = 1 To e.Row.Cells.Count
     e.Row.Cells(i).BackColor = Drawing.ColorTranslator.FromHtml("#d3f1c7")
Next

The exception was being thrown before it got the chance to move on to the next row. Since I wanted to skip the first cell, and apply the background color only to all subsequent cells, I had to set it to loop to one less than the count of cells, as such:

For i As Integer = 1 To e.Row.Cells.Count - 1
     e.Row.Cells(i).BackColor = Drawing.ColorTranslator.FromHtml("#d3f1c7")
Next

Upvotes: 1

Related Questions