user2411290
user2411290

Reputation: 641

C#: Outputting content from TextBox to Console when Button is Clicked

Sorry for the noob question...I would like to output the contents of the TextBox to the console every time a button is clicked. My TextBox variable, "textBox," is not being seen because I assume it is out of scope. I'm wondering what the correct way to go about this is.

Thank you.

class Test : Form
    {
        public Test()
        {
            Button btn = new Button();
            btn.Text = "Click Me";
            btn.Parent = this;
            btn.Location = new Point(100, 10);
            btn.Click += ButtonOnClick;

            TextBox textBox = new TextBox();
            textBox.Parent = this;
            textBox.Size = new Size(150, 25);
            textBox.Location = new Point(60, 60);

        }
        void ButtonOnClick(object objSrc, EventArgs args)
        {
           String message = textBox.Text;
           Console.WriteLine(message);
        }
    }
    class Driver
    {
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Test());
        }
    }
}

Upvotes: 0

Views: 1112

Answers (1)

Steve
Steve

Reputation: 216293

A WinForms application has no Console to write to. So you will never see anything outside a debug session with Visual Studio that supply a window to capture the Console.WriteLine output.
You could add a Console to a WinForms application but this is a total different matter

How do I show a Console output/window in a forms application

Said that, your problem is caused by the fact that you create two local variables for your controls but then you don't add them to the forms controls container and then exit from the constructor losing the two variables.

You should keep global class level variables for these controls

class Test : Form
{
    private Button btn;
    private TextBox textBox;

    public Test()
    {
        btn = new Button();
        btn.Text = "Click Me";
        btn.Parent = this;
        btn.Location = new Point(100, 10);
        btn.Click += ButtonOnClick;
        this.Controls.Add(btn);

        textBox = new TextBox();
        textBox.Parent = this;
        textBox.Size = new Size(150, 25);
        textBox.Location = new Point(60, 60);
        this.Controls.Add(textBox);

    }
    void ButtonOnClick(object objSrc, EventArgs args)
    {
       String message = textBox.Text;
       // This will be written to the Output Window when you debug inside
       // Visual Studio or totally lost if you run the executable by itself
       //Console.WriteLine(message);

       // WinForms uses MessageBox.Show
       MessageBox.Show(message);

    }
}

This is the code that you can find in the InitializeComponent written for you by the form designer when you add controls to the forms

Upvotes: 2

Related Questions