Geeks With Blogs
Bunch's Blog One day I'll have a catchy subtitle, one day

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" >
        <asp:BoundField DataField="PlayerName" HeaderText="Player Name" />
        <asp:BoundField DataField="PlayerNumber" HeaderText="Player Number" />
        <asp:TemplateField HeaderText="Errors">
                <asp:Label ID="lblErrors" runat="server" Text='<%# EVAL("Errors") %>'  />

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
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: ,,
Posted on Friday, June 17, 2011 9:44 AM | Back to top

Comments on this post: Accessing Controls Within A Gridview

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Bunch | Powered by: