如何从类文件中访问文本框

时间:2012-12-05 17:23:52

标签: c# class textbox

在C#中我想直接从页面访问文本框而不将其作为变量发送到类中,例如

file class.cs code

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;
    }
}

default.aspx.cs代码

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
}

这就是我想出来的,但我不确定我是否采用这种方式使用getter和setter采取正确的方法:

private TextBox TextBox1 = new TextBox();
public string  settext {
    get { return TextBox1.Text; }
    set { TextBox1.Text = value;}
}

但我总是收到NullReferenceException was unhandled消息。

2 个答案:

答案 0 :(得分:3)

将其添加到构造函数

A a = new A(this.TextBox1.Text);

public class A
{
    private String _Text;

    public A(String text){

       this._Text = text;
    }

}

私有_Text变量只能由类在内部访问,但是如果更改为public属性,则可以在创建实例后访问它

A a = new A(this.TextBox1.Text);
String text = a._Text;

除此之外,如果它是一个公共变量,那么你可以创建实例并设置_Text而不需要public A(String text)构造函数:

A a = new A();
a._Text = this.TextBox1.Text;
String seeIfSet = a._Text;

答案 1 :(得分:0)

我找到了我正在寻找的东西,它的工作就像魅力一样,我会按照我的方式行事,文章的链接帮助我弄清楚如何解决它 http://codebetter.com/jefferypalermo/2004/09/01/asp-net-2-0-master-pages-changes-the-pages-control-hierarchy-level-300/ 如果在我没有母版页的情况下使用母版页相同的想法,我使用的是母版页,我在有和没有工作的情况下都进行了测试

    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;
    }