INTRODUCTION
In this article, I am going to explain how to use a TextBox in a Windows Forms app using Visual Studio 2017.
TextBox Control
The textbox control is used to accept and display an input as a single line of text. This control has additional functionality that is not found in the standard windows textbox control, including Multiline editing and password character masking.
WinForms TextBox controls are used to get inputs from the user and to display the inputs. TextBox control is generally used for editing text, but it can also be set to read-only. TextBoxes are used to display multiple lines of wrap text to the size of the control. TextBox control allows a single format for text displayed or entered in it.
STEP 1 - Start the Project
Let's create a new project using Visual Studio 2017.
Select New Project-->Visual C#--->Windows Forms App (.NET Framework), give your project a name and click OK.
This action creates WinForms project with default form and you should see the Windows designer.
STEP 2 - Drag and Drop Control
Let's add a TextBox control to the form by dragging it from Toolbox and dropping it to the form. You will see a TextBox 1 is added to the form. This control is now available to you in the code behind.
Now, let's add another control to the form by dragging the other control from Toolbox to the form. You may also want to change the properties of the other controls. Let's add a Label and a Button control to the form.
Change the text of the button and label control to what you like.
STEP 3 - Coding for Button Click Event
You can add a button click event handler by simply double-clicking on the button control.
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button2_Click(object sender, EventArgs e)
- {
- MessageBox.Show(textBox1.Text);
- }
-
- private void textBox1_TextChanged(object sender, EventArgs e)
- {
-
- }
-
- private void label1_Click(object sender, EventArgs e)
- {
-
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- textBox1.Text = DateTime.Now.ToString();
- }
- }
STEP 4 - Compile and Run
Now simply compile and run the application.
Once you click on the Set Time button, the time and the date will be displayed in the TextBox.
Once you click on the Get Time button, the time and the date will be displayed in the MessageBox.
Summary
In this basic article, you saw how to use a TextBox control. I hope you found this article interesting. For any feedback, please post it as a comment at the bottom of this article. Thank you!