I'm trying to code a section for my website in VB but VB can't seem to find a button. Is there a way for the code to find it?
I know where it is. Loginview > Login > LoginTemplate. How do I get VB.NET to point to that location?
I'm trying to code a section for my website in VB but VB can't seem to find a button. Is there a way for the code to find it?
I know where it is. Loginview > Login > LoginTemplate. How do I get VB.NET to point to that location?
Since the button is in a template, you'll need to use the FindControl method.
For example, if you have markup like this:
<asp:LoginView ID="loginview1" runat="server">
<LoggedInTemplate>
<asp:Button ID="btn1" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
Then, in your code-behind, you'll need to reference it like this:
Button btn = loginview1.FindControl("btn1") as Button;
if (btn != null)
{
// do whatever you need here
}
Just for future reference, (I haven't tried Nate's code) sometimes you have to search the controls found in .Parent
, especially when trying to find controls in a container, or worse, in a container, in a container, in a container, etc.
or search child .Controls because on second read I can't tell if this is a parent location or a child location that is searching for a control. If you are in an ascx, generally you are searching parents, if you are in a page generally you are searching children.
Here is the automatic code converter: http://converter.telerik.com/ for C# to 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;
}
I hope this is suggestive of a solution, to really nail a solution, I'd need more of your source code.
TryCast
function in VB.NET is an analog of operator as
in C#:
Dim btn As Button = TryCast(Me.FindControl("Button1"), Button)
If btn IsNot Nothing Then
' use btn
End If
See also this topic and this. So are you sure that you're searching in current, active template?
Are you logged in on your site? If you are not logged in, your button won't be rendered on your page. (So you won't be able to find it with FindControl.)
Nate's code is correct as long as your LoginView is not inside another container (such as a master page or a placeholder.)
Dim btn As Button = Ctype(loginview1.FindControl("btn1"), Button)
If that doesn't work, add trace="true" in your page directive. Reload the page and look at the bottom under Control Tree. You should see a line like:
loginview1$btn1 System.Web.UI.WebControls.Button