schultz schultz - 1 year ago 113
C# Question

ErrorProvider - Change BackColor Instead of Showing Icon

I'm stuck with some legacy code that I want to upgrade a bit. I want to change the way the

shows the error status on a Control. Default behavior is the Icon, and a
if you hover on the icon.

I would like to change this behavior to be more similar to what we use in our WPF controls. Which is a red back-color(Salmon pink) and the tool-tip on the control itself.

Any tips, links or some way forward

See my answer below, on what i ended up with.

Answer Source

ErrorProvider component doesn't support this feature and if you need it you can create it yourself.

You can subscribe to BindingComplete event of a BindingManagerBase and then you can use the event arg which is of type BindingCompleteEventArgs that contains some useful properties:

  • ErrorText to determine if there is an error in data-binding
  • Binding.Control to determine the control which is bounded to

These are enough for us to implement our solution.


Here is a sample code which shows how can you handle BindingComplete event and use it to change BackColor and tool-tip of a control based on it's valid or invalid state.

Suppose you have a binding source, myBindingSource which is bound to a SampleModel class which is implemented IDataErrorInfo. You can subscribe to BindingComplete event of this.BindingContext[this.myBindingSource]:

private void Form1_Load(object sender, EventArgs e)
    this.myBindingSource.DataSource = new SampleModel();

    var bindingManager = this.BindingContext[this.myBindingSource];
    bindingManager.BindingComplete += bindingManager_BindingComplete;

Dictionary<Control, Color> Items = new Dictionary<Control, Color>();
private void bindingManager_BindingComplete(object sender, BindingCompleteEventArgs e)
    var control = e.Binding.Control;
    //Store Original BackColor
    if (!Items.ContainsKey(control))
        Items[control] = control.BackColor;

    //Check If there is an error
    if (!string.IsNullOrEmpty(e.ErrorText))
        control.BackColor = Color.Salmon;
        this.errorToolTip.SetToolTip(control, e.ErrorText);
        e.Binding.Control.BackColor = Items[e.Binding.Control];
        this.errorToolTip.SetToolTip(control, null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download