From Databinding and Nullable types in WinForms.NET
Scenario
- You have an Entity Type with a Nullable property.
- You have a TextBox which is bound to that property.
- When the user clears the text in the TextBox, you want the value of your property to be set to null.
Problem
The result of the databinding will simply not succeed when clearing a TextBox which is bound to a Nullable type.
Solution
In this article I am going to show how you can do this by using an Extender Provider.
Simply add a Component class to your project which also implements the IExtenderProvider interface
[ProvideProperty("NullableBinding", typeof(TextBox))]
public partial class NullableExtender : Component, IExtenderProvider
The ProviderProperty attribute indicates that when adding the NullableExtender component to your Form or UserControl, all the TextBoxes will have an additional property named NullableBinding. It will look something like this in the VS.NET designer:
Now to implement some functionality for this property:
private Dictionary<Control, Boolean> _nullables = new Dictionary<Control,bool>();
/// <summary>
/// This is the get part of the extender property.
/// It is actually a method because it takes the control.
/// </summary>
/// <param name="control"></param>
[DefaultValue(false),
Category("Data")]
public bool GetNullableBinding(Control control)
{
bool nullableBinding = false;
_nullables.TryGetValue(control, out nullableBinding);
return nullableBinding;
}
/// <summary>
/// This is the set part of the extender property.
/// It is actually a method because it takes the control.
/// </summary>
/// <param name="control"></param>
/// <param name="nullable"></param>
public void SetNullableBinding(Control control, bool nullable)
{
if (_nullables.ContainsKey(control))
_nullables[control] = nullable;
else
_nullables.Add(control, nullable);
if (nullable)
{
// Add a parse event handler.
control.DataBindings["Text"].Parse += new ConvertEventHandler(NullableExtender_Parse);
}
}
/// <summary>
/// When parsing, set the value to null if the value is empty.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NullableExtender_Parse(object sender, ConvertEventArgs e)
{
if (e.Value.ToString().Length == 0)
{
e.Value = null;
}
}
The code that actually does the trick above is adding the event handler for the databinding Parse event. The event handler simply sets the value to null if the value is an empty string, and the databinding succeeds.
The default value of the property is set to false since most properties are not of a Nullable type, and I would suggest not setting the NullableBinding to true for these properties... ;)