Beginner 10 min read Control #26

TextBox Control

TextBox is one of the most common controls. It allows users to enter and edit text.

What is a TextBox?

TextBox is used for user input. It can be single-line or multi-line, and supports password masking, read-only mode, and text validation.

Code Example

// Set text
txtName.Text = "John Doe";

// Get text
string name = txtName.Text;

// Make it a password box
txtPassword.PasswordChar = '*';

// Multi-line
txtDescription.Multiline = true;
txtDescription.ScrollBars = ScrollBars.Vertical;
txtDescription.WordWrap = true;

// Validation
private void txtEmail_TextChanged(object sender, EventArgs e)
{
    bool isValid = txtEmail.Text.Contains("@");
    btnSubmit.Enabled = isValid;
    lblValid.Visible = isValid;
}

// Clear text
txtName.Clear();

// Select all
txtName.SelectAll();

Exercise

Task: Create a simple contact form.

  • Add TextBoxes for First Name, Last Name, Email, Phone
  • Add a multi-line TextBox for address
  • Add a Password TextBox for password
  • Validate that email contains the @ symbol
  • Show a message when the user submits
  • Clear all fields after submission
Key Takeaway

TextBox is essential for user input. Use PasswordChar for passwords, Multiline for longer text, and TextChanged for validation.