ToolTip and ErrorProvider

Two components attach behaviour to other controls without being controls themselves. ToolTip shows a line of help when the pointer rests on a control, and ErrorProvider shows a small icon with a message next to a field whose value is wrong. Neither is drawn on the form at design time, and both appear in the component tray of the designer.

ToolTip

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 = "Help that waits"; ClientSize = new Size(400, 160); var tip = new ToolTip { AutoPopDelay = 8000, InitialDelay = 600, ReshowDelay = 100, ShowAlways = true, ToolTipTitle = "Code", ToolTipIcon = ToolTipIcon.Info, }; var code = new TextBox { Location = new Point(16, 16), Width = 180 }; var price = new NumericUpDown { Location = new Point(16, 52), DecimalPlaces = 2, Width = 120 }; var save = new Button { Text = "&Save", Location = new Point(16, 96) }; tip.SetToolTip(code, "A short code such as AB-123"); tip.SetToolTip(price, "The price without tax"); tip.SetToolTip(save, "Writes the record and closes the form"); Controls.Add(code); Controls.Add(price); Controls.Add(save); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. One ToolTip serves every control on the form: SetToolTip(control, text) registers the text, and the same component shows it wherever the pointer rests. A second component would be a second style, not a second tooltip per control.

ErrorProvider

An ErrorProvider marks the fields that are wrong and shows the message when the pointer rests on the icon. It is the control that makes a validation message sit next to its field instead of in a message box:

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 { private readonly TextBox _name = new() { Location = new Point(90, 18), Width = 200 }; private readonly NumericUpDown _price = new() { Location = new Point(90, 52), Width = 120 }; private readonly ErrorProvider _errors = new() { BlinkStyle = ErrorBlinkStyle.NeverBlink, BlinkRate = 500, }; public Form1() { Text = "Validated fields"; ClientSize = new Size(420, 160); var nameLabel = new Label { Text = "&Name:", Location = new Point(16, 22), AutoSize = true }; var priceLabel = new Label { Text = "&Price:", Location = new Point(16, 56), AutoSize = true }; var save = new Button { Text = "&Save", Location = new Point(16, 96) }; _errors.SetIconAlignment(_name, ErrorIconAlignment.MiddleRight); _errors.SetIconPadding(_name, 4); _name.Validating += (sender, e) => _errors.SetError(_name, _name.Text.Length == 0 ? "A name is required" : string.Empty); _price.Validating += (sender, e) => _errors.SetError(_price, _price.Value == 0m ? "A price must be greater than zero" : string.Empty); save.Click += (sender, e) => { if (!ValidateChildren()) { return; } MessageBox.Show("Saved", "Validated fields"); }; Controls.Add(nameLabel); Controls.Add(priceLabel); Controls.Add(_name); Controls.Add(_price); Controls.Add(save); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The rule lives in three places and each has a reason. Validating runs when the user leaves the field, so the message appears at the moment it can help. SetError(control, "") clears the icon, and the empty string is the only way to clear it. ValidateChildren() raises Validating on every control that can be validated and returns false when one of them cancelled, which is what makes the Save button check the whole form at once instead of each field in turn.

Two components, one rule

The two components answer different questions and a form needs both. A tooltip explains what a field is for before the user types; an error provider says what is wrong with what was typed. Neither is a validation rule: the rule is a method that returns a message, and the form decides how to show it. That separation is what the next part of the course builds on.

An error summary that runs

The rule that turns a field into a message is ordinary code, and the object behind SetError is a collection of field-and-message pairs. This program keeps such a collection and prints it, and it runs here:

using System; using System.Collections.Generic; using System.Linq; var errors = new ErrorSummary(); errors.Add("name", "A name is required"); errors.Add("date", "The date is not a date"); errors.Add("price", "A price must be a number"); errors.Add("price", string.Empty); Console.WriteLine($"errors: {errors.Count}"); foreach (var (field, message) in errors.All) { Console.WriteLine($"{field,-6} {message}"); } Console.WriteLine($"name set: {errors.Has("name")}"); Console.WriteLine($"price set: {errors.Has("price")}"); internal sealed class ErrorSummary { private readonly List<(string Field, string Message)> _items = new(); public int Count => _items.Count; public IReadOnlyList<(string Field, string Message)> All => _items; public bool Has(string field) => _items.Any(item => item.Field == field); public void Add(string field, string message) { _items.RemoveAll(item => item.Field == field); if (message.Length == 0) { return; } _items.Add((field, message)); } }

dotnet run

errors: 2
name   A name is required
date   The date is not a date
name set:    True
price set:   False

The output is the real run. The fourth call adds a price error and then clears it with an empty message, which is exactly what SetError(control, string.Empty) does to the icon, so the count is two. The summary keeps one message per field, because a field with two messages needs a decision about which one to show, and the decision belongs in the rule rather than in the collection. In a form this object is what the presenter returns after Validate(), and the view walks it with SetError.

Exercises

  1. Add a method that returns the messages as a single line for a status bar, and run the program.
  2. Make Add keep the first message for a field instead of the last, and run it again.
  3. Explain from the documentation what ValidateChildren does with a control whose CausesValidation is false.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many ToolTip components does a form with three controls need?

    Answer

    One: it registers the text of every control

    SetToolTip(control, text) registers each control on the same component.

  2. Which property is the time before the first tooltip appears?

    Answer

    InitialDelay

    AutoPopDelay is how long it stays and ReshowDelay the gap before the next.

  3. What does SetToolTip(control, "") do?

    Answer

    Removes the tooltip from that control

    An empty text is how a hint that stopped being true is withdrawn.

  4. Which call clears the error icon of a control?

    Answer

    SetError(control, string.Empty)

    The text is the state; an empty string means no error.

  5. What does ErrorBlinkStyle.NeverBlink do?

    Answer

    Shows the icon without animation

    It is the calm choice for a form that validates while the user types.

  6. Which calls place the error icon beside a named control?

    Answer

    SetIconAlignment and SetIconPadding

    The icon position is set per control on the provider, not on the provider itself.

  7. What does ValidateChildren() return?

    Answer

    false when a control cancelled its Validating event

    It is the whole-form check behind a Save button.

  8. What did the run print as the count?

    Answer

    2, because the price error was cleared by an empty message

    The fourth call cleared the third field's message.

  9. Why does the summary keep one message per field?

    Answer

    A field shows one icon and one message, so the rule must choose

    The decision about which message matters belongs in the rule.

  10. What is the difference between a tooltip and an error message?

    Answer

    A tooltip explains the field before typing; an error says what is wrong with the value

    One is help, the other is a verdict on what was entered.

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