我正在使用FindControl函数在页面上查找控件.它似乎在MSDN上超级简单直接但我无法让它找到控件.我正在使用的页面有一个MasterPageFile,它更多地包含了我在aspx文件中给出contorl的id.一个不起作用的简单示例:
aspx页面
<%@ Page Title="Inventory Control Test" Language="VB" AutoEventWireup="false" MasterPageFile="~/Site.master" CodeFile="Default2.aspx.vb" Inherits="Sales_ajaxTest_Default2" %>
<asp:Content ID="conHead" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="conBody" ContentPlaceHolderID="MainBody" Runat="Server">
<asp:Button ID="saveAllBtn" runat="server" Text="Save All" />
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
代码背后
Partial Class Sales_ajaxTest_Default2
Inherits System.Web.UI.Page
Protected Sub saveAllBtn_Click(sender As Object, e As System.EventArgs) Handles saveAllBtn.Click
Dim myControl1 As Control = FindControl("ctl00_MainBody_saveAllBtn")
If (Not myControl1 Is Nothing) Then
MsgBox("Control ID is : " & myControl1.ID)
Else
'Response.Write("Control not found.....")
MsgBox("Control not found.....")
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
结束班
我知道msgbox不是一个web事物,我只是在这个例子中使用它.如果我使用"saveAllBtn",这是给控件的id,在FindControl中我得到"控件未找到".如果我试试这个,在没有母版页的独立页面上工作正常.
如果我使用chrome检查元素,我发现按钮的ID已更改为"ctl00_MainBody_saveAllBtn",但如果我在FindControl中使用它,我仍然会"找不到控件"
当您使用FindControl时,您将指定控件的"服务器ID"(您将其命名为),而不是控件的最终呈现的"客户端ID".例如:
Dim myControl as Control = MainBody.FindControl("saveAllBtn")
Run Code Online (Sandbox Code Playgroud)
但是,在您的具体示例中,由于您处于saveAllBtn.Click事件中,因此您要查找的控件实际上是sender参数(因为您单击该按钮以触发您所在的事件)ex:
Dim myControl as Button = CType(sender, Button)
Run Code Online (Sandbox Code Playgroud)
如果你只是想找到saveAllBtn控制权,wweicker 的第二种方法using CType(sender, Button)是首选。
但是,如果您想通过名称查找其他控件,则不能仅使用FindControl. 您需要递归地查找该控件,因为它嵌套在其他控件内。
这是辅助方法 -
Protected Sub saveAllBtn_Click(sender As Object, e As EventArgs)
Dim button = TryCast(FindControlRecursive(Me.Page, "saveAllBtn"), Button)
End Sub
Public Shared Function FindControlRecursive(root As Control, id As String) As Control
If root.ID = id Then
Return root
End If
Return root.Controls.Cast(Of Control)().[Select](Function(c) FindControlRecursive(c, id)).FirstOrDefault(Function(c) c IsNot Nothing)
End Function
Run Code Online (Sandbox Code Playgroud)
注意:我的 VB 代码可能有点奇怪,因为我用 C# 编写并使用转换器转换为 VB 。