Wednesday, May 7, 2008

Changing the Page Title from server side in ASP.NET

Some times we need to change the page title of the page from the server side code. For this, there are two simple methods to set the the page title.

We can directly assign the page title form server side as Page.Title="MyPageTitle". But one main thing is that we must set the <head> tag as runat="server".

<head runat="server">

And remove the <title></title> tag from the <head> tag.

The second method is that,
put the runat="server" and id in the Title tag.

<title id="MyPageTitle" runat="server"> My Page Title </title>

After making the title tag as server control we can easily access the title from server by Id specified in the title tag. If you are using files from VS2003, then we need to declare title as protected.

protected System.Web.UI.HtmlControls.HtmlGenericControl MyPageTitle;


(Later versions of visual studio does not need this over head. The VS automatically add this declaration in designer file.)

The HtmlGenericControl type objects have a property named "InnerText" and we can set the new page title there.

MyPageTitle.InnerText="MyNewPageTitle";