Data binding with nullable types in C#

Binding a nullable type to a control in C# doesn’t seem to be as simple as binding a normal primary type. Firstly, if you want to bind a nullable type to a textbox, remember to set FormattingEnable property of the Binding to be true. Otherwise, you will find that every time you try to type in some value in the textbox and step away from it, it clears the value. Secondly, you will find that leaving the textbox empty doesn’t tell the nullable type to set itself to null. To achieve that affect, you need to take care of the Binding instance’s Parse event. Suppose you try to bind a nullable<double> to a textbox, remember to hook the following event to the Parse event of the Binding instance:

void Text_Parse(object sender, ConvertEventArgs e){if(e.Value == null || e.value.ToString().Length == 0) e.Value = null;}

After hooking this event to the Binding instance, clear the textbox content will set the underlying nullable<double> to null.

Until next time, happy coding.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s