Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to databind a Winforms control to a nullable type?

Tags:

I'm currently using winforms databinding to wire up a data editing form. I'm using the netTiers framework through CodeSmith to generate my data objects. For database fields that allow nulls it creates nullable types. I've found that using winforms databinding the controls won't bind properly to nullable types.

I've seen solutions online suggesting that people create new textbox classes that can handle the nullable types but that could be a pain having to swap out the textboxes on the forms I've already created.

Initially I thought it would be great to use an extension method to do it. Basically creating an extension property for the textbox class and bind to that. From my limited extension method experience and doing a bit of checking online it looks like you can't do an extension property. As far as I can tell, binding has to be through a property since it needs to be able to get or set the value so an extension method wouldn't work.

I'd love to find a clean way to retrofit these forms using something like extension methods but if I have to create new textbox and combo box controls that's what I'll do.

My project is currently limited to .Net 2.0 due to the requirement to run on Windows 2000.

Any suggestions?

like image 935
Steve Hiner Avatar asked Dec 17 '08 22:12

Steve Hiner


1 Answers

In the comments section of the article referenced above one of the posters comes up with a simple solution.

Instead of binding with:

textBox1.DataBindings.Add("Text", myClass, "MyTextProperty"); 

Bind with:

textBox1.DataBindings.Add("Text", myClass, "MyTextProperty", true, DataSourceUpdateMode.OnPropertyChanged, string.Empty);  
like image 50
shindigo Avatar answered Oct 13 '22 12:10

shindigo