.NET Active Server页面FindControl始终不返回任何内容

Ted*_*tel 0 .net vb.net asp.net

我用一个按钮创建了一个简单的页面,然后在click事件上让它使用FindControl来获取对它自己的引用.但是...... FindControl什么都没回来.码

Protected Sub EntryDoor1_Click(sender As Object, e As System.EventArgs) Handles EntryDoor1.Click
    Dim control = FindControl("EntryDoor1")
    control.Visible = False
End Sub
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 6

因为你已经说过你想要"引用它自己",所以我假设你想要一个引起点击事件的按钮的引用.

最简单的方法是使用sender参数,因为它始终是源控件:

Dim button = DirectCast(sender, Button)
Run Code Online (Sandbox Code Playgroud)

但是当按钮位于页面顶部时(如本例所示),将在部分designer.vb文件中自动创建对控件的引用:

 EntryDoor1.Visible = False
Run Code Online (Sandbox Code Playgroud)

那么为什么要使用,FindControl如果你有直接参考呢?!

编辑:

只是为了完整.你所描述的行为只能有一个原因:你试图FindControl在a ContentPage中使用MasterPage.这是一个特例,你需要得到ContentPlaceholder第一个的引用.然后你可以使用FindControl你的Button:

Dim button = DirectCast(Page.Master.FindControl("ContentPlaceHolder1").FindControl("EntryDoor1"), Button)
Run Code Online (Sandbox Code Playgroud)

但同样,这是毫无意义的,因为您直接在页面中有引用.