In this post I showed how nullable types can be simulated in .NET 1, especially for use with XPO. Prompted by Miha Markic, I had a look at the possibility of data binding with those simulated nullable types. I found that while the implementation I had suggested could be used without problems in a read-only situation, it obviously didn’t contain any logic that would enable editing the types via data-bound controls. Nevertheless, this is easy to do by creating a custom TypeConverter. Like this:

public class NullableInt32TypeConverter : TypeConverter {
  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
    if (sourceType == typeof(string))
      return true;
    return base.CanConvertFrom(context, sourceType);
  }

  public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
    if (value is string) {
      try {
        int intVal = Convert.ToInt32(value);
        return new NullableInt32(intVal);
      }
      catch (FormatException) {
        return new NullableInt32( );
      }
    }

    return base.ConvertFrom(context, culture, value);
  }
}

To activate this type converter for NullableInt32, you have to decorate the NullableInt32 class with an attribute:

[TypeConverter(typeof(NullableInt32TypeConverter))]
public class NullableInt32 : Nullable {
  public NullableInt32( ) : base(false) { }
  ...

Now you can bind a collection of objects, which contain properties of the type NullableInt32, to a grid and edit the value for the NullableInt32 property. Just enter an invalid or empty string to set the value to null.

Update: Miha pointed me to this obviously more complete implementation of nullable types for .NET 1. I haven’t had a close look at them because my platform is .NET 2 anyway, so I can’t say anything about the implementation, but obviously the main purpose of this post was to show a way of implementing this kind of thing with XPO. I guess that information in usable with the sourceforge implementation of nullable types just the same.