master page from the content page I have Run code ...">

Cannot access the <input type = "button"> master page from the content page

I have

<input type="button" id="Button1">
      

Run code


in my main page Master1.master

. (which is in <div>

).

I also have a content page Main.aspx

. I want to set the visibility of a button true

when I access a content page Main.aspx

, for example from another page. (I have a page Login.aspx

, and after I insert user / psw and click a button, I am redirected to Main.aspx

).

I have added a directive <%@ MasterType virtualpath="~/Master1.master" %>

and I am using the following code

Button home = new Button();
home = (Button)Master.FindControl("Button1");
home.Visible = false;

      

However, when I try to run this, I get NullReferenceException

. So basically I don't see "Button1". I tried changing the values ​​to head

or ContentHolder1

and it works great with them.

Can anyone help me?

+3


source to share


3 answers


You cannot access an input that is not server side:

You will need:



<input type="button" id="Button1" runat="server">

      

+3


source


You need to add an attribute runat

:



<input type="button" id="Button1" runat="server">

      

+2


source


Ask the master page to open the property, which you can then use to link to Button

. The ID of the control will change during the render event; so you cannot find it. Using a property on the master page, you can refer to a control by referring to a variable Page.Master

. You will need to translate it into your home page class so you can use IntelliSense to access your friends' public methods / properties. Here's the code ... sorry it's in VB.

Here is the main HTML page.

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" id="button1" runat="server" />
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

      

Here is the code for the main page.

Partial Class MasterPage
    Inherits System.Web.UI.MasterPage
    Public ReadOnly Property Button As Control
        Get
            Return button1
        End Get
    End Property
End Class

      

Here is the content page.

Partial Class Default2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        CType(Page.Master, MasterPage).Button.Text = "My Text"
    End Sub
End Class

      

Note the display name of the control below; they are not what you expect. You can get the real rendered name from the UniqueID property.       

+1


source







All Articles