Reputation: 2171
In C# i would like to access textbox from page directly without sending it as variable to the class for example
public class A {
private string dosomething {
string text;
text = textbox1.text;
// textbox1 exists in, for example, default.aspx, and I need it's
// value in the class after some event occurred - let's say there
// is button and it was clicked
return text;
}
}
protected void Button1_Click(object sender, EventArgs e) {
A a = new A();
// I need when this button clicked to fill the variable within
// the class with the data given from the textbox within this page
}
This is what I've come up with, but I'm not sure if I'm taking the right path using a getter and setter this way:
private TextBox TextBox1 = new TextBox();
public string settext {
get { return TextBox1.Text; }
set { TextBox1.Text = value;}
}
but I always get a NullReferenceException was unhandled
message.
Upvotes: 1
Views: 2015
Reputation: 2171
i found what i'm looking for and it's working like charm i will put the way i did and the link for the article helped me to figure out how to solve it http://codebetter.com/jefferypalermo/2004/09/01/asp-net-2-0-master-pages-changes-the-pages-control-hierarchy-level-300/ in case using master page same idea for without master page in my case i was using master page and i tested it on both with and without working fine
private TextBox gettextbox ( )
{
//without master page
/*System.Web.UI.Page Default = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
TextBox TextBox1 = (TextBox)Default[0].FindControl("TextBox1");*/
//with master page
System.Web.UI.Page Default = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
ContentPlaceHolder cph = Default.Controls[0].FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
TextBox Textbox1 = (TextBox)cph.FindControl("TextBox1");
return Textbox1;
}
Upvotes: 0
Reputation: 5594
Add it to the constructor
A a = new A(this.TextBox1.Text);
public class A
{
private String _Text;
public A(String text){
this._Text = text;
}
}
The private _Text variable can be accessed internally by the class only, however if you change to a public
property you can access it after creating an instance
A a = new A(this.TextBox1.Text);
String text = a._Text;
Further to this, if it was a public variable then you can just create the instance and set the _Text and would not need the public A(String text)
constructor:
A a = new A();
a._Text = this.TextBox1.Text;
String seeIfSet = a._Text;
Upvotes: 3