【问题标题】:Problem finding web control inside of Gridview TemplateField在 Gridview TemplateField 中查找 Web 控件时出现问题
【发布时间】:2009-08-17 15:26:58
【问题描述】:

好的,所以在更新我的 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

【问题讨论】:

  • 我实际上可以使用 RowCommand 事件,但知道如何做到这一点仍然很好。 :)

标签: asp.net gridview findcontrol


【解决方案1】:

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

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

您已经在下拉列表中指定了&lt;%# Bind(...) %&gt;,因此 ASP.NET 将为您完成查找控件和获取新值的工作 - 您不必自己探查控件层次结构。

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 2013-10-10
    • 2011-10-15
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多