Search code examples
vb.netcontrolsmaster-pages

How to pass value to master pages user control


I have problem. I have site.master which includes a couple of user controls. Now I need to pass value (string) from actual pages code behind to master pages user control (Property) .

So my master is like this:

<%@ Master Language="VB" CodeFile="/scripts/pohjakoodit.master.vb" Inherits="pohjakoodit"  AutoEventWireup="false"  debug="false" %>

... on the end of master there is:

<ucSheriff:sheriffala ID="sheriffala" statvalue="atesti" runat="server" />

Then I have actual page which starts like this:

<%@ Page Language="vb" MasterPageFile="site.master" AutoEventWireup="false" CodeFile="/scripts/alkuuutisetxw.aspx.vb" Inherits="uutiset_index" debug="true"  %>

The sheriffala.ascx has property

dim Public staref As String = ""    

    Public Property statvalue() As String
        Get
            Return statvalue
        End Get
        Set(ByVal value As String)
            staref = value
        End Set
    End Property

Now I try to access property statvalue from user control sheriffala in code behind file alkuuutisetxw.aspx.vb.

I have tried the very basics like sheriffala.statvalue = "my srting" or page.master.sheriffala.statvalue = "my srting" And tried couple of binding, non of them have't worked out.

So how do I pass a string to user controls property from code behind file?


Solution

  • You need to make sure your UserControl is Public on your MasterPage. Then in the CodeBehind of your ContentPage, you need to create an instance of your MasterPage and you should be good to go to access statvalue(), since it's already Public.

    Or if you don't like messing with the designer file, you can make properties that expose your UserControls and MasterPage:

    MasterPage:

    Public ReadOnly Property UCSheriffala() As Sheriffala
        Get
            Return Me.Sheriffala
        End Get
    End Property
    

    Content Page:

    Public Shadows ReadOnly Property Master() As Pohjakoodit
        Get
            Return CType(MyBase.Master, Pohjakoodit)
        End Get
    End Property
    

    Usage Example:

    Response.Write(Master.UCSheriffala.statvalue)