Accessing Controls Within A Gridview

Posted by Bunch on Geeks with Blogs See other posts from Geeks with Blogs or by Bunch
Published on Fri, 17 Jun 2011 07:44:11 GMT Indexed on 2011/06/20 16:24 UTC
Read the original article Hit count: 225

Filed under:

Sometimes you need to access a control within a GridView, but it isn’t quite as straight forward as just using FindControl to grab the control like you can in a FormView. Since the GridView builds multiple rows the key is to specify the row. In this example there is a GridView with a control for a player’s errors. If the errors is greater than 9 the GridView should display the control (lblErrors) in red so it stands out. Here is the GridView:

<asp:GridView ID="gvFielding" runat="server" DataSourceID="sqlFielding" DataKeyNames="PlayerID" AutoGenerateColumns="false" >
    <Columns>
        <asp:BoundField DataField="PlayerName" HeaderText="Player Name" />
        <asp:BoundField DataField="PlayerNumber" HeaderText="Player Number" />
        <asp:TemplateField HeaderText="Errors">
            <ItemTemplate>
                <asp:Label ID="lblErrors" runat="server" Text='<%# EVAL("Errors") %>'  />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In the code behind you can add the code to change the label’s ForeColor property to red based on the amount of errors. In this case 10 or more errors triggers the color change.

Protected Sub gvFielding_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvFielding.DataBound
    Dim errorLabel As Label
    Dim errors As Integer
    Dim i As Integer = 0
    For Each row As GridViewRow In gvFielding.Rows
        errorLabel = gvFielding.Rows(i).FindControl("lblErrors")
        If Not errorLabel.Text = Nothing Then
            Integer.TryParse(errorLabel.Text, errors)
            If errors > 9 Then
                errorLabel.ForeColor = Drawing.Color.Red
            End If
        End If
        i += 1
    Next
End Sub

The main points in the DataBound sub is use a For Each statement to loop through the rows and to increment the variable i so you loop through every row. That way you check each one and if the value is greater than 9 the label changes to red. The If Not errorLabel.Text = Nothing line is there as a check in case no data comes back at all for Errors.

Technorati Tags: ,,

© Geeks with Blogs or respective owner