.Net:在Windows应用程序中填写窗体上的一些组合框的最佳技术?

时间:2010-05-26 10:30:32

标签: .net winforms combobox fill

假设您有一个包含5个组合框的获胜表单。

有人告诉我你必须要有5个数据表才能逐个填写。它似乎不合逻辑,我认为这会产生丑陋的代码。

如何使用存储在数据库中的数据填充它们?

3 个答案:

答案 0 :(得分:4)

我使用的类看起来像这样:

Public Class ComboboxBinder(Of TKey, TValue)
    Inherits List(Of KeyValuePair(Of TKey, TValue))

    Public Sub New()
    End Sub

    Public Overloads Sub Add(ByVal key As TKey, ByVal value As TValue)
        MyBase.Add(New KeyValuePair(Of TKey, TValue)(key, value))
    End Sub

    Public Sub Bind(ByVal control As ComboBox)
        control.DisplayMember = "Value"
        control.ValueMember = "Key"
        control.DataSource = Me
    End Sub

End Class

然后使用它你会放这样的东西:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim binder As New ComboboxBinder(Of Guid, String)
    binder.Add(Guid.NewGuid, "Item 1")
    binder.Add(Guid.NewGuid, "Item 2")
    binder.Add(Guid.NewGuid, "Item 3")
    binder.Add(Guid.NewGuid, "Item 4")

    binder.Bind(ComboBox1)

End Sub

Winforms是如此痛苦的绑定,但这个解决方案适用于我们公司。 另外值得注意的是,您无法绑定到Dictionary,它必须是IListIListSource,因此Combobox活页夹为List<KeyValuePair<TKey,TValue>> < / p>

答案 1 :(得分:1)

就个人而言,我认为WinForms数据绑定很痛苦,所以我用“for”循环手动完成。我只需循环遍历单个数据集,并在该循环中向每个组合框添加元素。

注意:我永远不会想到在WPF中这样做 - 它的数据绑定机制要好得多......

答案 2 :(得分:1)

BindingSource可能是您在Windows窗体中最好的朋友。

然后您可以分配BindingSource.DataSource属性。将ComboBox设置为设计时,即将ComboBox.DataSource个属性设置为BindingSource的实例,您现在需要的只是填充BindingSource

请参阅我对this SO question的回答,以查看使用BindingSource类的Windows窗体数据绑定的大致演练。

对于每个ComboBox策略的表,这可能很有用,因为每个层次结构可以有一个表。在这里,我们更可能讨论一个对象关系持久性策略,这可能是一个漫长的过程。简而言之,请参阅此NHibernate参考文档和Chapter 8. Inheritence Mapping以获取更多详细信息。您更可能会关注Three Strategies

现在我知道了,在你的问题中你没有提到NHibernate等。我的目标是简单地向您展示一些最受欢迎的实体持久性策略,这是您的问题间接询问的。