Updating an asp:label control in Visual Basic.Net
In Visual Basic.Net you have control over the text shown in the HTML via the <asp:label> control. With a proper id of the label, you can update the properties of the label in the code-behind.
I have used this technique for example in the Masterpage from the website of Justitia Digitalis to make a variable <h1> element for each page. The HTML looks like this:
<h1 id="h1head"> <asp:Label ID="lblHead" runat="server" Text="Headertekst"></asp:Label> </h1>
Used in a normal page the label could be updated in the code-behind in this way:
me.lblHead.Text = "Some new text"
If you place the code given above on a Masterpage, and try to alter te text in the code-behind of a child page, you encouter a problem: you can't use a construction like:
me.Master.lblHead.Text = "Text from the Child page"
Your child page can't reach the asp:label on the Masterpage.
Use a public method or property on the Masterpage
A simple solution is the following: add a public property on your Masterpage. In the code of this property you encapsulate the methods of the asp:label. The code in the Masterpage to update only the text of the label is like this:
Public Property Head() As String Get Head = lblHead.Text End Get Set(ByVal NewValue As String) lblHead.Text = NewValue End Set End Property
In the code-behind of your child page you can use this public property like this:
me.Master.Head = "Text from the Child page"
If you want to have full control over the label on the Masterpage, change the property to the following:
Public Property Head() As Label Get Head = lblHead End Get Set(ByVal NewValue As Label) lblHead = NewValue End Set End Property
The child page can control all of the properties of the label now.
The same technique can be used to have even more control over the Masterpage. You can define for example a Public method on the Masterpage with a parameter, that is used to retrieve data from a database. Another powerful use is to make an asp:panel visible or hide it, depending on a parameter.
|