Question

With ASP.Net 2.0 you can use the Title property to change the page title :

Page.Title = "New Title";

But since in ASP.Net 1.1 there isn't a Title property in the Page class, how can I change the page's title from the code-behind ?

Was it helpful?

Solution

With ASP.Net 1.1, first you have to set the runat attribute on the title markup :

<title id="PageTitle" runat="server">WebForm1</title>

Then from the code behind :

C#

// We need this name space to use HtmlGenericControl
using System.Web.UI.HtmlControls;

namespace TestWebApp
{

      public class WebForm1 : System.Web.UI.Page
      {
            // Variable declaration and instantiation
            protected HtmlGenericControl PageTitle = new HtmlGenericControl();

            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Set new page title
                  PageTitle.InnerText = "New Page Title";
            }
      }
}



VB

Imports System.Web.UI.HtmlControls

Namespace TestWebApp

    Public Class WebForm1
        Inherits System.Web.UI.Page

        Protected PageTitle As HtmlGenericControl = New HtmlGenericControl()

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

            PageTitle.InnerText = "New Page Title"
        End Sub

...

    End Class
End Namespace

OTHER TIPS

The answer by Andreas Grech works very well when running it from the code behind of the ASPX page that has the TITLE tag.

But what if the TITLE tag needs to be updated from a Web User Control ran from the ASPX page? The above would result in an error (because PageTitle is not visible to the Web User Control).

So in the case of a Web User Control, do as Grech's solution dictates, but make the following adjustments:

1) Do not declare the PageTitle control before Page_Load. Instead:

2) Declare it inside Page_Load as follows:

Dim PageTitle as HtmlGenericControl = Page.FindControl("PageTitle")

And then set the value.

In here main point is that if you set title in your master page in

<head><title>Master Title</title></head>

Your code to add title in code side will not work.Even everything is correct

Page.Title="Page Title"

This one above not effective. You have to remove title from master page. After that no need to extra code.Just add this code below in Page_Load

Page.Title="Page Title"

And it will work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top