Search code examples
c#winformsdatagridviewenumsdatagridviewcombobox

Empty value in datagridview combobox dropdown for nullable type


I have a nullable enum binding to a combobox cell. The comboxbox style is set to dropdown.

Since my enum is nullable, I am expecting the Dropdown to have an empty value, but that doesn't seem to be the case.

Is there any built-in way of enforcing this, other than adding a "NULL" value to the enum and keeping track of that?


Solution

  • As far as I know, Windows Forms binding doesn't have anything like the WPF TargetNullValue property, so the only possible way is to handle the Format and Parse events:

    Binding binding = new Binding // ..
    comboBox.DataBindings.Add(binding);
    
    binding.Format += (sender, eventArgs) =>
    {
        if (eventArgs.Value == null)
            eventArgs.Value = "NULL";
        else
            eventArgs.Value = eventArgs.Value.ToString();
    }
    
    binding.Parse += (sender, eventArgs) =>
    {
        if (eventArgs.Value == "NULL")
            eventArgs.Value = null;
        else
            eventArgs.Value = Enum.Parse(typeof(MyEnum), eventArgs.Value.ToString());
    }