Find Label Control Inside ContentBody - asp.net

I have a label control on a page (test1.aspx) that has a master page. I want to access a label control from the code behind of the test1.aspx page (not the master page) using FindControl.
I can make it work going directly using Button2 (see below) but I want to be able to do it using FindControl (see Button1 below). I'm getting a NULLReference exception I believe because I don't know the proper syntax to target the label control inside a content control.
On a page without a Master page I would just use FindControl("MenuItemName1") but because the control is in the Content3 / ContentBody I believe I need more. Any help would be greatly appreciated.
<%# Page Title="" Language="VB" MasterPageFile="~/Shared/MasterPages/SiteLayout.Master" AutoEventWireup="false" CodeFile="Test1.aspx.vb" Inherits="Test1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="StyleSheetPage" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentBody" Runat="Server">
<asp:Label ID="lblMenuItemName1" runat="server" Text="Label"></asp:Label><br /><br />
<asp:Button ID="Button1" runat="server" Text="Button" /><br /><br />
<asp:Button ID="Button2" runat="server" Text="Button" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="JavaScriptPage" Runat="Server">
</asp:Content>
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim C As Content
C = CType(Me.FindControl("Content3"), Content)
Dim lblMenuItemName As Label = C.FindControl("lblMenuItemName1")
lblMenuItemName.Text = "hello"
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
lblMenuItemName1.Text = "Direct"
End Sub

Found the solution:
Dim lblMenuItemName As Label = TryCast(Master.FindControl("ContentBody").FindControl("lblMenuItemName1"), Label)

Related

Why is my UserControl Visible property always returning false?

I have an issue where the Visible property on my user control is always returning False despite whether it should be visible on the page or not. I have the following user control:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="VB_WebApp_Test.WebUserControl1" %>
<h1>My User Control</h1>
Public Class WebUserControl1
Inherits UserControl
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.PreRender
If Visible Then
Console.WriteLine("VISIBLE")
End If
End Sub
End Class
That I load into the following page:
<%# Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.vb" Inherits="VB_WebApp_Test.Default" %>
<%# Register src="WebUserControl1.ascx" tagName="WebUserControl" tagPrefix="Mine"%>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<tr>
<td>
<asp:MultiView runat="server" ID="multiView">
<asp:View ID="vInit" runat="server">
<h1>Initial View</h1>
<asp:Button runat="server" ID="toControlButton" Text="To Control"/>
</asp:View>
<asp:View ID="vControl" runat="server">
<Mine:WebUserControl ID="wuc1" runat="server"/>
<asp:Button runat="server" ID="toNonControlButton" Text="To Non Control"/>
</asp:View>
</asp:MultiView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Public Class [Default]
Inherits Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
multiView.ActiveViewIndex = 0
End Sub
Public Sub ToControl(sender As Object, e As EventArgs) Handles toControlButton.Click
multiView.ActiveViewIndex = 1
End Sub
Public Sub ToNonControl(sender As Object, e As EventArgs) Handles toNonControlButton.Click
multiView.ActiveViewIndex = 0
End Sub
End Class
What I would like to do is make it so that I can do some initialisation logic when the user control will be displayed, but the Visible property is always set to False. I have tried hooking onto the Load, PreRender and Init events, and the Visible property is False for all of them.
When your ActiveViewIndex is updated in Click event of button, the sequence of event is:
1) Load for Page, ActiveIndex is 0, UC is not visible.
2) Load for UserControl, UC is not visible due to invisible View
3) Processing of events, ActiveIndex is updated to 1, Visibility property is updated for all related controls
4) Page.LoadComplete event (Visible is True already, but you do not have the event)
5) Page.PreRender (Visible is True already, but you do not have the event yet)
6) UC.PreRender - here you should see Visible=True.
I've just tedsted this on empty project and it works. You've must missed something when checking the PreRender event.
Init based on Visibility is not very good practice. I suggest you to add some initialization like this:
Public Sub Init()
'Do init here
End Sub

asp.net output from a SOAP page location using response.write

I hope someone can help. I created a webservice and it returns XML via SOAP fine and well. It transforms fine with XSLT and I return the HTML to a ASP VB.net webform.
I call the functions in the code behind with a button.
Everything works great except the transformed output always ends up at top of the page. I return the result to a label, put the label in a different contentplaceholder but it always is on top. I want the input items(text box) and button to float at the top.
Here is the very simple main webform - plus a bit from where the results are coming from.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="WebForm1.aspx.vb" Inherits="WS_NewCar.WebForm1" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<p>
<img src="images/barner.jpg" style="width: 508px; height: 198px; margin-left: 280px" /></p>
<p>
</p>
<p>
<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
</p>
<p>
</p>
<p>
</p>
<p>
<br />
Click here for SOAP request. <asp:Button ID="btnConvert" runat="server" Text="Search" />
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<asp:Label ID="lblMake" runat="server" Text="Please enter vehicle make"></asp:Label>
</asp:Content>
Dim sr As New StreamReader(memoryStream)
response.Write(sr.ReadToEnd())
sr.Close()
End Function
Protected Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
lblMake.Text = callWS(txtInput.Text)
End Sub
Response.Write(sr.ReadToEnd()) will always render at the top of the page. It is called before the page is rendered. Try changing it by adding a label where you want the output to appear and do the following in your page_load
label1.Text = sr.ReadToEnd()

Visual Basic subprocedure issue

I'm working on some .NET code in visual studio web developer and I'm having an issue. When I double click on a button in design view, instead of loading a subprocedure, all it does is highlight this: <asp:Button ID="btnEnter" runat="server" Text="Enter" onclick="btnEnter_Click" />
When I try to run that just to see what happens, I get this error:
Line 8: <asp:Button ID="btnEnter" runat="server"
Compiler Error Message: BC30456: 'btnEnter_Click' is not a member of 'ASP.default_aspx'.
If I erase the onclick="btnEnter_Click" and run it, it works. Either way though, when I double click the button / element, shouldn't it create a subprocedure for me that looks something like?
Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
I've tried entering that manaully but the keywords don't turn blue or any sort of color, and when I run it, it just shows up as text on the webform with my other elements. Here is all I have so far:
<%# Page Title="Home Page" Language="VB"%>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Enter a person's name below"></asp:Label>
<p>
<asp:TextBox ID="txtStudentName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button ID="btnEnter" runat="server"
Text="Enter" onclick="btnEnter_Click" />
</p>
<p>
<asp:Button ID="btnDisplay" runat="server" Text="Display all and exit" />
</p>
<p>
<asp:Label ID="lbl2" runat="server" Text=" "></asp:Label>
</p>
<p>
<asp:Label ID="lbl3" runat="server" Text=" "></asp:Label>
</p>
<p>
<asp:Label ID="lbl4" runat="server" Text=" "></asp:Label>
</p>
<p>
<asp:Label ID="lbl5" runat="server" Text=" "></asp:Label>
</p>
</form>
Edit:
When I enter my code inside the default.aspx.vb file, it highlights keywords and such, but it can't reference the elements I created in the design view.
Partial Class _Default
Inherits System.Web.UI.Page
End Class
Class Lab1
Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Public Const length As Integer = 3
Shared counter2 As Integer = 0
Public Shared studentList As String() = New String(2) {}
Protected Sub btnEnter_Click(sender As Object, e As EventArgs)
Label1.Text = "Enter a person's name"
Dim studentName As [String] = txtStudentName.Text
If studentList.Length <= length Then
If txtStudentName.Text <> "" Then
Dim match As [Boolean] = True
Dim i As Integer = 0
While counter2 >= i
If studentList(i) IsNot Nothing Then
If studentList(i).ToUpper() = txtStudentName.Text.ToUpper() Then
match = False
Label1.Text = "This name has already been used"
End If
End If
i += 1
End While
If match = True Then
studentList(counter2) = txtStudentName.Text
counter2 += 1
End If
End If
End If
End Sub
End Class
Your Page declaration seems to say you are using inline style:
<%# Page Title="Home Page" Language="VB"%>
Which means your code is/should be within aspx file itself in a script runat="server" tag:
<%# Page Language="VB" %>
<!DOCTYPE html>
<script runat="server">
Protected Sub Button1_Click(sender As Object, e As EventArgs)
'Do something
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
However, your other code indicates you seem to want to use code-behind model, where you have .vb files (e.g. foo.aspx.vb)
The Page is declared like this for web sites (for web applications it will say CodeBehind="foo.aspx.vb"):
<%# Page Language="VB" AutoEventWireup="false" CodeFile="foo.aspx.vb" Inherits="foo" %>
You will find a foo.asp.vb file in your project
it's class name will be the name of your file (foo)
your code should be scoped to this class (I'm not sure what Class Lab1 in your post above is for....
foo.aspx.vb:
Partial Class foo
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Do something
End Sub
End Class
The "fix" is for you to:
choose which model you want to write code: inline or code-behind
declare the Page appropriately
for inline, your code will be in the aspx file itself
for code-behind, your code will live, and should be encapsulated within the Class file of the page.
The Page declaration actually says so:
CodeFile="foo.aspx.vb" is the file where the code is
Inherits="foo" is the Partial Class in the file (Partial Class foo)
Try this
Private Sub btnEnter_Click(sender As Object, e As System.EventArgs) Handles btnEnter.Click
End Sub
Here, btnEnter_Click is your event name and use the Handles keyword at the end of a procedure declaration to cause it to handle events raised by an object variable

Understanding UpdatePanels

I am trying to understand UpdatePanels and best practise for using them.
I am using .Net4.0 with VB.Net.
The idea is to create a conversation app for a clients website and so I have control called Convo.ascx. Code added below.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<h2>Conversation</h2>
<p><asp:Literal ID="lit1" runat="server" /></p>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
Convo.ascx.vb
Partial Class Convo
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lit1.Text = lit1.Text & "<p>" & TextBox1.Text & "</p>"
End Sub
End Class
On a load page (Default.aspx) I have:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%# Reference Control="~/Convo.ascx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Add Conversation" />
<asp:PlaceHolder ID="phConversation" runat="server">
</asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
With Codebehind Default.aspx.vb as
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddConvo()
End Sub
Private Sub AddConvo()
Dim getPh As New PlaceHolder
getPh = CType(Me.FindControl("phConversation"), PlaceHolder)
Dim ucConvo As New Convo
ucConvo = CType(LoadControl("~/Convo.ascx"), Convo)
getPh.Controls.Add(ucConvo)
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
AddConvo()
End Sub
End Class
So the Convo I add OnLoad remains on the page after extra as been added been any convo added after load is gone once the button on Convo is hit.
So my question is, how can I have these add and remain? Eventually they will be added to database but right now I am trying to understand UpdatePanels as they will become the foundation for this app.
Is there a very good explanation of multi-use UpdatePanels anywhere?
Thanks in advance
PS, im a hobbiest so only VB responses please
The issue actually isn't with the UpdatePanel, but with ASP.NET. ASP.NET web forms uses a control hierarchy for the entire page, and you are adding the controls to the hierarchy "dynamically". Since you are doing it that way, ASP.NET requires you add the control back into the control hierarchy on every postback to the server. The UpdatePanel is a way to post back to the server, and therefore you must re-add the old user controls and new ones to that hierarchy.
Essentially the UpdatePanel was added to make AJAX easy, but you still have to work within the rules of ASP.NET.

Making changes to a pre-populated textbox

I have the following webform with textboxes that are pre-populated on page load:
<%# Page Title="" Language="VB" MasterPageFile="~/default.master" AutoEventWireup="true" CodeFile="admin.aspx.vb" Inherits="admin" Theme="G2M" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="form1" Runat="Server">
<label>Username: </label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<label>Password: </label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<label>Product Type: </label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<label>SMTP Default Only: </label>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<br />
<label>Logo: </label>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<br />
<asp:Button ID="submit" Text="Submit changes" runat="server" OnClick="SubmitChanges" />
</form>
</asp:Content>
And the codebehind is as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmlDoc As New XmlDocument
xmlDoc.Load(Server.MapPath("~/XML_Config/Config.xml"))
Dim configValues As XMLParser = New XMLParser(xmlDoc) ''Instantiate the XMLParser
''Populate textboxes with XML data
TextBox1.Text = configValues.UserName
TextBox2.Text = configValues.Password
TextBox3.Text = configValues.ProductType
TextBox4.Text = configValues.SMTPDefaultOnly
TextBox5.Text = configValues.Logo
End Sub
Public Sub SubmitChanges(ByVal sender As Object, ByVal e As System.EventArgs)
Dim xmlDoc As New XmlDocument
xmlDoc.Load(Server.MapPath("~/XML_Config/Config.xml"))
Dim configValues As XMLParser = New XMLParser(xmlDoc) ''Instantiate the XMLParser
configValues.SMTPDefaultOnly = TextBox4.Text
End Sub
All I'm trying to do is make the values editable so when the form is presented to the user, they can change the values and submit them back to the file. My problem is that when the SubmitChanges function is called, even though I change the value of the textbox, it is still the same. How do I pass a new value, typed into thetextbox, to the function?
Enclose your setter in If Not ispostback in that page load. It's overwriting the boxes.

Resources