Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...