Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c# - Accessing Form variable from outside of a method

public class Simple : Form
{
    public Simple()
    {
        Text = "Server Command Line";
        Size = new Size(800, 400);
        CenterToScreen();
        Button button = new Button();
        TextBox txt = new TextBox ();
        txt.Location = new Point (20, Size.Height - 70);
        txt.Size = new Size (600, 30);
        txt.Parent = this;
        txt.KeyDown += submit;
        button.Text = "SEND";
        button.Size = new Size (50, 20);
        button.Location = new Point(620, Size.Height-70);
        button.Parent = this;
        button.Click += new EventHandler(sSubmit);   
    }

    private void submit(object sender, KeyEventArgs e)
    {
       if (e.KeyCode == Keys.Enter ) {
            Console.WriteLine ("txt.Text");//How do I grab this?
            Submit();
        }
    }
}

I'm trying to access txt.Text from outside the Form, and google hasn't been helpful either. How do I access it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your txt variable is declared within the local scope of the Simple() constructor. You will not be able to access it anywhere outside of this scope like you are doing in your submit method.

What you may want to do is create a private instance variable within your Simple class that you will then be able to access from any method declared that belongs to this class.

Example:

public class Simple : Form
{
    //now this is field is accessible from any method of declared within this class
    private TextBox _txt;
    public Simple()
    {
        Text = "Server Command Line";
        Size = new Size(800, 400);
        CenterToScreen();
        Button button = new Button();
        _txt = new TextBox ();
        _txt.Location = new Point (20, Size.Height - 70);
        _txt.Size = new Size (600, 30);
        _txt.Parent = this;
        _txt.KeyDown += submit;
        button.Text = "SEND";
        button.Size = new Size (50, 20);
        button.Location = new Point(620, Size.Height-70);
        button.Parent = this;
        button.Click += new EventHandler(sSubmit);   
}

private void submit(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.Enter ) {
        Console.WriteLine (_txt.Text);//How do I grab this?
        Submit ();
    }
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...