Catching a string from a textbox when you press the Enter key [closed]

1

Is it possible to get a string from a textbox when the enter key is pressed? If yes, how? I would like you to leave code examples as I am quite new to this WinForms world ...

    
asked by anonymous 02.09.2015 / 14:42

1 answer

1

You can associate the code that will use the TextBox content with an event that fires when a key is pressed while the TextBox has the focus. >

You can use the KeyDown event of the TextBox component. To do so, select the component in the form and in the Properties window, click the pointing button to see the event list, locate the KeyDown event and double-click it:

In the FormName file, visual studio will generate a code like this:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{

}

And you'll also associate this method with the KeyDown event of the TextBox component (in this case, my TextBox name is textBox1 ). / p>

Visual Studio did this:

private void InitializeComponent()
    {
        ...
        this.textBox1.KeyDown += 
                    new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
        ...
    }
}

Finally, in the body of the method that Visual Studio generated in FormName , enter the text handling code of the TextBox. Example:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.Enter)
    {
        MessageBox.Show(textBox1.Text);
    }  
}

Note that it is not enough to write the code above, this method must be associated with the event of the textbox component.

Study how WinForms programming is event-driven, and understand the code generated by Visual Studio.

    
02.09.2015 / 15:57