There’s a lot of “goodness” buried in WinForms databinding that doesn’t get to see the light of day. Here’s one example I discovered just today …

When you set up a Binding, one of the possible parameters is a boolean value for enable formatting:

    var binding 
        = new Binding(
            "EditValue",  // Name of the control property to bind
            aSubject,     // Data source
            aProperty,    // Path of property on the data source
            true,         // Is Formatting Enabled
            DataSourceUpdateMode.OnPropertyChanged);

The interesting thing is that turning enable formatting on does more than enable the Format and Parse events.

Check out the OnFormat() method of the Binding object, for example:

    protected virtual void OnFormat(ConvertEventArgs cevent)
    {
        if (onFormat != null)
        {
            onFormat(this, cevent);
        }

        if (!formattingEnabled
            && !(cevent.Value is DBNull)
            && cevent.DesiredType != null
            && !cevent.DesiredType.IsInstanceOfType(cevent.Value)
            && cevent.Value is IConvertible)
        {
            cevent.Value
                = Convert.ChangeType(
                    cevent.Value,
                    cevent.DesiredType,
                    CultureInfo.CurrentCulture);
        }
    }

If you turn on formatting, you also turn on automatic conversions between types that implement IConvertible. Amongst other things, this allows you to databind to nullable properties.

Neat.

Comments

blog comments powered by Disqus
Next Post
False positive from Gendarme?  09 May 2009
Prior Post
How not to set up Tests  17 Apr 2009
Related Posts
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
April 2009
2009