代码之家  ›  专栏  ›  技术社区  ›  BioXhazard

找到一个asp:Button in VB.NET版

  •  1
  • BioXhazard  · 技术社区  · 16 年前

    我试图用VB为我的网站编写一段代码,但是VB似乎找不到按钮。代码有办法找到它吗?

    我知道在哪儿。Loginview>登录>登录模板。如何让VB.NET指向该位置?

    4 回复  |  直到 16 年前
        1
  •  2
  •   Nate Dudek    16 年前

    因为按钮在模板中,所以需要使用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
    }
    
        2
  •  0
  •   abatishchev Karl Johan    16 年前

    TryCast as 在C#:

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

    另请参见 this topic this . 所以你确定你在当前的活动模板中搜索吗?

        3
  •  0
  •   MatthewMartin muthu    16 年前

    只是为了将来的参考,(我没有试过内特的代码)有时你必须搜索在中找到的控件 .Parent ,尤其是在试图在容器中找到控件时,或者更糟的是,在容器中,在容器中,在容器中,等等。

    http://converter.telerik.com/ 对于C#到VB.NET

    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;
    }
    

        4
  •  0
  •   kc.    16 年前

    你登录过你的网站吗?如果您没有登录,您的按钮将不会显示在您的页面上(所以您将无法使用FindControl找到它。)

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

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

    推荐文章