Access page control from class file in App_Code

| October 27, 2010 | 5 Comments

Simple tasks seems hard while development. I too faced the issue of accessing page controls from class files in App_Code folder. But since each and everything is possible in development. This one appears impossible first but now the matter has been resolved. Check it out how…

Scenario

You are having simple .aspx page with two controls Label and Button. You have added a class file Hello.cs in App_Code folder in your web application. And you want to access the Page’s label control in class file.

How to Do?

We have simply used System.Web.HttpContext.Current.Handler property to access page’s controls. Then cast it into System.Web.UI.Page type. See code snippet below:

Hello class

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;</pre>
public class Hello
{
public Hello()
{ }

public string Test()
{
string strValue = null;

// Accessing Page's Controls
Page page = (Page)HttpContext.Current.Handler;
Label lblName = (Label)page.FindControl("lblText");

if (lblName != null)
{
strValue = "Mission accomplished!";
}

return strValue;
}
}

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;</pre>
public partial class _Default : System.Web.UI.Page
{
protected void btnShow_Click(object sender, EventArgs e)
{
Hello obj = new Hello();
Response.Write(obj.Test());
}
}

Category: Asp.Net, Tips

Comments (5)

Trackback URL | Comments RSS Feed

  1. Ahmed Fahmy says:

    Wonderful, That’s what i have been looking for. Thank You!

  2. Anonymous says:

    i have used ur code … but it is unable to find the controls present in the page attached with masterpage..

    how to find the controls of page attached to masterpage?????

  3. Anonymous says:

    hii i have used your fine its working
    but if the page is attached with masterpage then it is unable to find the controls … how to do that..??
    in class file the controls in page attached with masterpage..???

    Please reply

  4. V.S. Saini says:

    Would you share your code where it is not working.

  5. Anonymous says:

    Not working….

Leave a Reply

%d bloggers like this: