Search code examples
asp.nethttpcontext

Access TextBox value of an ASP.NET page from C# class


Say there is a TextBox on an ASP.NET page

<asp:TextBox id="DateTextBox" runat="server" />

with some value set in the code-behind.

How to access that value from another class of C# code-file through HttpContext or any other way?


Solution

  • You can access a property in you page via HttpContext even from a static method.

    in your page:

    public string DateTextBoxText
    {
        get{ return this.DateTextBox.Text; }
        set{ this.DateTextBox.Text = value; }
    }
    

    somewhere else(even in a different dll):

    public class Data
    {
       public static string GetData() 
       { 
           TypeOfYourPage page = HttpContext.Current.Handler as TypeOfYourPage;
           if (page != null)
           {
              return page.DateTextBoxText;
              //btw, what a strange method!
           }
           return null;
        }
    }
    

    Note that this works only if it's called from within a lifecycle of this page.

    It's normally better to use ViewState or Session to maintain variables across postback. Or just use the property above directly when you have a reference to this page.