Problem with DataBinding and Custom Formatters

I tried the following code to format a databound control with custom formatting.  When you step through the code, the Format method is never called for the custom formatter, it always defaults to the global Format function.  This to me seems like a pretty major bug in Microsoft's databinding implementation.  Anyone else notice this?  Here is the sample code:

Below is the form binding data to a label to use  a custom formatter:

namespace BindingFail

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

// binding a custom formatter to

Binding b = label2.DataBindings.Add("Text", numericUpDown1, "Value", true, DataSourceUpdateMode.OnPropertyChanged, "<not specified>", "{0}.555", new MyCustomFormatterNamespace.CustomFormatter());

// use this to fix the problem

//b.Format += new ConvertEventHandler( new 

// MyCustomFormatterNamespace.CustomFormatter());

}

private void Form1_Load(object sender, EventArgs e)

{
 
label2.Text = "5545";
}

}

}

And here is the custom formatter:

 

using System;

namespace MyCustomFormatterNamespace

{

public class CustomFormatter : ICustomFormatter, IFormatProvider

{

#region ICustomFormatter Members

public string Format(string format, object arg, IFormatProvider formatProvider)

{

return String.Format("Success! (#.00", arg);

}

#endregion

#region IFormatProvider Members

public object GetFormat(Type formatType)

{

if (formatType == typeof(ICustomFormatter))

return this;

else

return null;

}

#endregion

}

}

 

note that only the global custom formatter is requested in GetFormat and  as a result CustomFormatter's Format is never called.

A little frusterating considering that DataBindings.Add takes a CustomFormatter arguement and never uses it.

 

Note:There is an O'Reilly book on DataBinding that may explain this, but I haven't had a chance to read it yet.

Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET
by Brian Noyes

Ebook Download
View all
Learn
View all