Access to BoundField value when GridView row is selected.

I have a GridView with BoundField , and  I want to access it value when  GridView row is selected:

            <asp:GridView ID=”grvCascadeRulesTemplates” runat=”server” AutoGenerateColumns=”False” DataKeyNames=”CascadeRuleKey” DataSourceID=”odsCascadeRulesTemplates”>

                <Columns>

                    <asp:CommandField ShowSelectButton=”True”

                     SelectText=”Show Values”>asp:CommandField>

                    <asp:BoundField DataField=”CascadeRuleKey” HeaderText=”CascadeRuleKey” ReadOnly=”True”

                        SortExpression=”CascadeRuleKey” />

                    <asp:BoundField DataField=”SourceTable” HeaderText=”Source Table” SortExpression=”SourceTable” />

                Columns>

            asp:GridView>

        Protected Sub grvCascadeRulesTemplates_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grvCascadeRulesTemplates.SelectedIndexChanged

            DebugHelper.PrintChildren(grvCascadeRulesTemplates.SelectedRow)

 

        End Sub

I have valid SelectedRow , but I didn’t find a way to easily get reference to control in the BoundField.

I don’t want to hardcode access the individual cells of the GridViewRow object by using the Cells property with numeric (non-mnemonic) index.. I can not  use the FindControl method , because the control doesn’t have an ID.
The possible solutions that I found (from some places including here) are:

1. Convert column to template and add an ID to be able use FindControl. Quite simple, but adds more markup code that I actually need.

2. Add my data column to  DataKeyNames – should work, but my data field is not part of primary key, so it is confusing.

3. Search GridView.Columns by my ColumnName to find index of the cell. I preferred it.

DataControlFieldCollection doesn’t provide Find method and furtermore the base class DataControlField doesn’t have ID or Name property, so I have to search by FooterText , HeaderText  or SortExpression. Alternatively I can cast DataControlField to BoundField and use DataField.

I choose SortExpression as it is less likely to change and should be the same as DataField.

I’ve included helper functions  CellBySortExpression,ColumnBySortExpression, GetColumnValueBySortExpression into my WebFormsHelper class

 

Advertisements