Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

.net - Best way to databind a Winforms control to a nullable type?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...