在VB.NET中找到一个asp:Button

时间:2010-06-14 12:02:17

标签: asp.net vb.net find

我正在尝试用VB为我的网站编写一个部分,但VB似乎找不到按钮。有没有办法让代码找到它?

我知道它在哪里。登录视图>登录> LoginTemplate。如何让VB.NET指向该位置?

4 个答案:

答案 0 :(得分:2)

由于按钮位于模板中,因此您需要使用FindControl方法。

例如,如果你有这样的标记:

<asp:LoginView ID="loginview1" runat="server">
        <LoggedInTemplate>
            <asp:Button ID="btn1" runat="server" />
        </LoggedInTemplate>
    </asp:LoginView>

然后,在您的代码隐藏中,您需要像这样引用它:

Button btn = loginview1.FindControl("btn1") as Button;

if (btn != null)
{
     // do whatever you need here
}

答案 1 :(得分:0)

仅供将来参考,(我还没有尝试过Nate的代码)有时您必须搜索.Parent中找到的控件,尤其是在尝试查找容器中的控件时,或者更糟糕的是,在容器中,容器,容器等

或搜索子.Controls因为在第二次读取时我无法判断这是父位置还是正在搜索控件的子位置。如果你在ascx,通常你正在寻找父母,如果你在一个页面,一般你正在寻找孩子。

这是自动代码转换器:C#到VB.NET的http://converter.telerik.com/

private static Control FindControl(Control container,string id)
{
    if (container.FindControl(id) != null)
        return container.FindControl(id);
    foreach (Control possibility in container.Controls)
    {
        if (container.FindControl(id) != null)
            return container.FindControl(id);
        if(possibility.Controls.Count>0)
        {
            Control childPossibility = FindControl(possibility, id);
            if (childPossibility != null)
                return childPossibility;
        }
    }
    //throw new InvalidOperationException("Couldn't find it!");
    return null;
}

我希望这是一个解决方案的暗示,真正确定解决方案,我需要更多的源代码。

答案 2 :(得分:0)

VB.NET中的

TryCast函数是C#中运算符as的模拟:

Dim btn As Button = TryCast(Me.FindControl("Button1"), Button)
If btn IsNot Nothing Then
    ' use btn
End If

另请参阅this topicthis。那么你确定你在当前的活动模板中搜索吗?

答案 3 :(得分:0)

您是否在您的网站上登录?如果您尚未登录,则您的按钮将不会在您的页面上呈现。 (因此,您无法使用FindControl找到它。)

只要您的LoginView不在另一个容器(例如母版页或占位符)内,Nate的代码就是正确的。

Dim btn As Button = Ctype(loginview1.FindControl(“btn1”),Button)

如果这不起作用,请在page指令中添加trace =“true”。重新加载页面并查看控制树下的底部。您应该看到如下行:

loginview1 $ btn1 System.Web.UI.WebControls.Button