Search code examples
c#eventscomponentsextendiextenderprovider

How to extend control events IExtenderProvider?


Is there a way to add events to a control like adding properties to a control with IExtenderProvider?

I try to write an own validtor with an errorpovider. with IExtenderProvider i'm adding the errorprovider and the errortext to the control. now i need to fire an event out of my extenderclass.

Snippet:

[ProvideProperty("ErrorText", typeof(TextBox))]
[ProvideProperty("ErrorProvider", typeof(TextBox))]
class ValidatorExtender : Component, IExtenderProvider {
    public bool CanExtend(object extendee) {
        return extendee is TextBox;
    }


    [DefaultValue(""), Category("Data")]
    public string GetErrorText(Control control) {
        //---------------------------
        //Return the ErrorText
        //---------------------------
        }
    }

    public void SetErrorText(Control control, string value) {
        //---------------------------
        //Assigning the ErrorText
        //---------------------------
    }

    [DefaultValue(null), Category("Data")]
    public ErrorProviderEX GetErrorProvider(Control control) {
        //---------------------------
        //Return the ErrorProvider
        //---------------------------
    }

    public void SetErrorProvider(Control control, ErrorProviderEX value) {
        //---------------------------
        //Assigning the ErrorProvider
        //---------------------------
    }
                                               //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    public event ValidatingHandler Validating; // -> The event I want to add to the Controls
                                               //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    void Control_Leave(object sender, EventArgs e) {
        if(Validating != null){
            Validating(this, new ValidatingEventArgs());
            //--------------------------
            // Assign Error if necessary
            //--------------------------
        }
    }
}

Solution

  • The SetErrorText method is your key. You need to keep a List<> of controls for which you have error text. You add the control to the list in SetErrorText when it is not already in the list. And subscribe its Validating event. You remove it from the list when the value argument is null or empty. And unsubscribe the event. This is well explained in the MSDN Library article for IExtenderProvider, check the code for the SetHelpText() method in the example given there.

    There's a problem in the way you do it, a control could set the error text but not the ErrorProvider. Or the other way around, neither is good. It is best to keep your own ErrorProvider as a private member of your class or assignable through a property. One is enough.