Using .NET 1 Nullable Types With Data Binding

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.

Sorry, this blog does not support comments.

I used various blog hosting services since this blog was established in 2005, but unfortunately they turned out to be unreliable in the long term and comment threads were lost in unavoidable transitions. At this time I don't want to enable third-party services for comments since it has become obvious in recent years that these providers invariably monetize information about their visitors and users.

Please use the links in the page footer to get in touch with me. I'm available for conversations on Keybase, Matrix, Mastodon or Twitter, as well as via email.