将 Winforms 控件数据绑定到可为空类型的最佳方法? [英] Best way to databind a Winforms control to a nullable type?

查看:34
本文介绍了将 Winforms 控件数据绑定到可为空类型的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 winforms 数据绑定来连接数据编辑表单.我通过 CodeSmith 使用 netTiers 框架来生成我的数据对象.对于允许空值的数据库字段,它创建可空类型.我发现使用 winforms 数据绑定控件将无法正确绑定到可为空类型.

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.

由于需要在 Windows 2000 上运行,我的项目目前仅限于 .Net 2.0.

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

有什么建议吗?

推荐答案

在上面引用的文章的评论部分,其中一位海报提出了一个简单的解决方案.

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

而不是绑定:

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

绑定:

textBox1.DataBindings.Add("Text", myClass, "MyTextProperty", true, DataSourceUpdateMode.OnPropertyChanged, string.Empty); 

这篇关于将 Winforms 控件数据绑定到可为空类型的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆