Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
84RR1573R Avatar asked Dec 01 '25 12:12

84RR1573R


1 Answers

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.

like image 63
Tim Schmelter Avatar answered Dec 06 '25 23:12

Tim Schmelter