在Gridview TemplateField中查找Web控件的问题

时间:2009-08-17 15:26:59

标签: asp.net gridview findcontrol

好的,所以在更新GridView时,我遇到了在TemplateField中获取DropDownList值的问题。最初我使用RowCommand事件来检查命令名称,然后执行相应的任务(更新/删除),但我遇到了两次事件触发的问题,因此我将其切换为单独的事件(RowUpdating,RowDeleting)。执行此操作后,FindControl每次都返回null。仅供参考,gridview位于UpdatePanel内部,其中包含用于RowEditing,RowUpdating和RowDeleting事件的AsyncPostBackTriggers。

这是我在GridView中的TemplateField:

<asp:TemplateField HeaderText="Type">
    <ItemTemplate>
        <asp:Label 
            ID="lblMedTypeEdit" 
            Text='<%# Bind("medDesc") %>' 
            runat="server">
        </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:DropDownList 
            ID="ddlMedTypeEdit" 
            DataSourceID="srcMedTypes" 
            SelectedValue='<%# Bind("medtype") %>' 
            runat="server" 
            DataTextField="medDesc" 
            DataValueField="medCode">
        </asp:DropDownList>                             
    </EditItemTemplate>
</asp:TemplateField>

这是我在

中使用的代码
Protected Sub gvCurrentMeds_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvCurrentMeds.RowUpdating
    Dim intRowIndex As Integer = e.RowIndex
    Dim ddlMedType As DropDownList = CType(Me.gvCurrentMeds.Rows(intRowIndex).Cells(1).FindControl("ddlMedTypeEdit"),DropDownList)
End Sub

我也尝试使用递归函数来查找控件(如下所示),但它仍然返回null。

Public Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
    If root.ID = id Then
        Return root
    End If

    For Each c As Control In root.Controls
        Dim t As Control = FindControlRecursive(c, id)
        If Not t Is Nothing Then
            Return t
        End If
    Next
    Return Nothing
End Function

1 个答案:

答案 0 :(得分:1)

如果您只想知道下拉列表的新值是什么,那么已经在传递给事件处理程序的NewValues对象的GridViewUpdateEventArgs属性中为您提供了这个值。

在您的示例中,e.NewValues["medtype"]应为更新后的值。

您已经在下拉列表中指定了<%# Bind(...) %>,因此ASP.NET将完成查找控件并为您获取新值的工作 - 您不必自己检测控件层次结构。< / p>