首页 > 解决方案 > Gridview 中的显式迭代并使用 findControl 返回 Nothing

问题描述

我正在尝试遍历 GridView 控件。它包含单选按钮,我想根据特定条件设置它的选中属性。但是,findControl 方法不返回任何内容。

这是aspx代码:

<asp:GridView ID="GridViewInfo"
                runat="server"
                AutoGenerateColumns="False"
                DataKeyNames="Result_ID">
    <Columns>
        <asp:TemplateField HeaderStyle-Width="3%" HeaderText="SELECT">
            <ItemTemplate>
                <input name="RadioButtonResultID" 
                       id="RadioButtonResultID" type="radio" 
                       value='<%# Eval("Result_ID") %>'/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Characteristics" 
                        DataField="Characteristics" />
    </Columns>
</asp:GridView>

后面的代码:

    Private Sub HighlightSelectedRow(ByVal id As String)
        Dim rowCount As Int32 = 0

        For Each row As GridViewRow In GridViewLabInfo.Rows
            If (GridViewLabInfo.DataKeys(rowCount).Value.ToString() = id) Then
                row.CssClass = "SelectedRowStyle"

                'Both of the below lines are failing
                TryCast(row.FindControl("RadioButtonResultID"), RadioButton).Checked = True
                CType(row.FindControl("RadioButtonResultID"), RadioButton).Checked = True

            End If
            rowCount = rowCount + 1
        Next
    End Sub

标签: asp.netvb.net

解决方案


You cast is wrong. That is not a asp.net radio button (RadioButton), but is a HTML one,

So your cast in in this case should be:

TryCast(row.FindControl("RadioButtonResultID"), HtmlInputRadioButton ).Checked = True

And you don't even need the cast, but this should work:

Dim MyRadioBut As HtmlInputRadioButton = row.FindControl("RadioButtonResultID")
MyRadioBut.Checked = True

However, in BOTH of the above cases? You can't pick up the control in code behind unless you state that control is rendered by the server.

You need to add the runat="server".

eg this:

 <input name="RadioButtonResultID" 
                   id="RadioButtonResultID" type="radio" 
                   value='<%# Eval("Result_ID") %>' runat="server" />

推荐阅读