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

社会主义新天地 提交于 2019-12-23 18:55:17

问题


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?


回答1:


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.




回答2:


You can create a public property within the control that returns a reference to the textbox.

You can then use this property to reference the textbox.

OR

You can store in into session and then access it in your entire application.




回答3:


Store it in the HttpContext Session http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net

//Storing UserName in Session
Session["DateTextBox"] = DateTextBox.Text;

Now, let's see how we can retrieve values from session:

//Check weather session variable null or not
if (Session["DateTextBox"] != null)
{
 // use it...
}



回答4:


You could place the value in the Session during the post back. Then access it from the Session in the other class. So in your form load event write this:

Session["MyValue"] = DateTextBox.Text

and then in the other class write this:

var val = HttpContext.Current.Session["MyValue"];


来源:https://stackoverflow.com/questions/15450158/access-textbox-value-of-an-asp-net-page-from-c-sharp-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!