TextBox
A TextBox is the field a user types into. It holds one string, reports every change through TextChanged, and can be a single line, a paragraph, a password or a read-only value. The rules about what is allowed in it are the application's, not the control's: a text box will accept any character it is given, which is why a WinForms application needs a filter of its own.
A field
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
public Form1()
{
Text = "Text boxes";
ClientSize = new Size(440, 300);
var code = new TextBox
{
Location = new Point(16, 16),
Width = 180,
PlaceholderText = "AB-123",
MaxLength = 6,
CharacterCasing = CharacterCasing.Upper,
};
var password = new TextBox
{
Location = new Point(16, 56),
Width = 180,
UseSystemPasswordChar = true,
};
var notes = new TextBox
{
Location = new Point(16, 100),
Size = new Size(400, 140),
Multiline = true,
AcceptsReturn = true,
ScrollBars = ScrollBars.Vertical,
WordWrap = true,
PlaceholderText = "Notes for this order",
};
var readOnly = new TextBox
{
Location = new Point(16, 252),
Width = 400,
ReadOnly = true,
BackColor = SystemColors.Control,
Text = "Created 2026-11-21, read-only",
};
Controls.Add(code);
Controls.Add(password);
Controls.Add(notes);
Controls.Add(readOnly);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The PlaceholderText is the grey hint that disappears at the first character, CharacterCasing upper-cases as the user types, MaxLength stops the input at six characters, and UseSystemPasswordChar draws dots instead of letters. The multi-line box accepts Enter, wraps at the right edge and shows a vertical scroll bar. The read-only box keeps a SystemColors.Control background, because a white read-only field looks editable.
The properties
- Text: the whole content, newlines included. It is a string, never null: an empty box gives "".
- Multiline and AcceptsReturn: the first turns the box into a small editor, the second lets Enter insert a line break instead of pressing the form's default button.
- PasswordChar and UseSystemPasswordChar: the masking character, or the system one. Neither encrypts anything: the value is in Text like any other.
- MaxLength: the number of characters the user can enter. A paste longer than that is cut.
- ReadOnly: the text cannot be changed and cannot be selected for editing, but it can be copied.
- ScrollBars, WordWrap and AcceptsTab: the parts of a multi-line box's behaviour that matter for a notes field.
TextChanged
Every keystroke, every paste and every assignment to Text raises TextChanged. That makes it the wrong place for validation that shows a message box, and the right place for cheap reactions: enabling a button, updating a filter, counting characters. Validation belongs to Validating (lesson 034), which runs when the user leaves the field instead of on every character.
There is one trap in TextChanged: a handler that assigns Text raises the event again. A handler that reformats the input must guard against its own assignment:
using System;
using System.Globalization;
using System.Windows.Forms;
internal sealed class AmountBox : TextBox
{
private bool _formatting;
protected override void OnTextChanged(EventArgs e)
{
if (_formatting)
{
base.OnTextChanged(e);
return;
}
_formatting = true;
try
{
if (decimal.TryParse(Text, NumberStyles.Number, CultureInfo.InvariantCulture, out var value))
{
Text = value.ToString("N2", CultureInfo.InvariantCulture);
SelectionStart = Text.Length;
}
}
finally
{
_formatting = false;
}
base.OnTextChanged(e);
}
}
That block is a class on its own: it has no Main, so the checker counts it and does not build it. The _formatting flag is the whole point, and so is SelectionStart at the end of the new text, without which the caret jumps to the front after every keystroke.
A filter that runs
The rule "this field takes digits only" is application logic, and it belongs in a plain class that can be tested. The program below is the rule without a control around it, and it runs here, because it draws nothing:
using System;
using System.Text;
var input = new[] { "12a", "4 5", "007", "a1b2c3" };
foreach (var text in input)
{
Console.WriteLine($"{text,-6} -> {KeepDigits(text)}");
}
Console.WriteLine($"fields: {input.Length}");
static string KeepDigits(string text)
{
var digits = new StringBuilder();
foreach (char c in text)
{
if (char.IsAsciiDigit(c))
{
digits.Append(c);
}
}
return digits.ToString();
}
dotnet run
12a -> 12
4 5 -> 45
007 -> 007
a1b2c3 -> 123
fields: 4
The output is the real run of that program on the machine of this page. In the form, the same function is called from KeyPress to refuse a character before it appears, or from TextChanged to clean up after a paste, because a paste never goes through KeyPress at all. That split, a rule in a class and two calls of it from the control, is the subject of the structure part of the course.
Exercises
- Add a field to the filter that keeps a decimal point and prints 12.50 for 1a2.5b0.
- Make the filter a class with a method and call it from a loop, then run it here.
- Explain why the AmountBox sets SelectionStart after the assignment.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does Text return for an empty text box?
Answer
An empty string, never null
TextBox.Text is always a string; an empty box gives the empty string.
-
Which property lets Enter insert a line break in a multi-line box?
Answer
AcceptsReturn
Multiline makes the box tall; AcceptsReturn decides what Enter does.
-
What does UseSystemPasswordChar protect?
Answer
Nothing: it only draws the characters as dots
The value is in Text like any other; masking is visual only.
-
Which event fires on every change of the text, including a paste?
Answer
TextChanged
KeyPress sees keys, not a paste; TextChanged sees the result.
-
Why is TextChanged the wrong place for a validation message box?
Answer
It fires on every character, so the message would appear while the user types
Validating runs when the user leaves the field, which is when a message is useful.
-
What goes wrong if a TextChanged handler assigns Text without a guard?
Answer
The event is raised again, and the handler re-enters
A flag around the assignment is the usual answer, as in the AmountBox class.
-
Why set SelectionStart after reformatting the text?
Answer
So the caret stays at the end instead of jumping to the front
Assigning Text resets the caret position, which is visible as a jump on every keystroke.
-
What does the headless filter program print for a1b2c3?
Answer
123
The run printed a1b2c3 -> 123, which is the rule applied to that input.
-
Which characters does char.IsAsciiDigit accept?
Answer
The ten ASCII digits 0 to 9
Unicode digits from other scripts are excluded, which is usually the stricter rule a field wants.
-
Why does a paste need a different guard than a key press?
Answer
A paste changes the text without a KeyPress for each character
KeyPress sees the keystrokes; a paste arrives as a whole string in Text.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev