views:

54

answers:

3

hi Suppose that you have a win form with 5 combo boxes on it.

Some one told me that you must have 5 data table in order to fill them one by one. It does not seem very logical and I think this will create ugly code.

How do you fill them with data stored in Database?

+1  A: 

Personally, I think WinForms databinding is painful, so I do it manually with "for" loops. I would just loop through a single dataset and add elements to each combo box in a that loop.

NOTE: I would never think of doing this in WPF -- it's databinding mechanism is much better...

Dave Markle
+4  A: 

I use a class that looks something like this:

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

then to use it you would put something like this:

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 is such a pain with binding, but this solution works well enough for our company. Also worth noting is that you cannot bind to a Dictionary, it must be an IList or and IListSource, hence why the Combobox binder is a List<KeyValuePair<TKey,TValue>>

Pondidum
+1  A: 

The BindingSource can be your best friend in Windows Forms.

You then may assign the BindingSource.DataSource property. Having bound your ComboBoxes on design-time, that is, setting each of the ComboBox.DataSource property to your instance of BindingSource, all you now need is to fill your BindingSource.

Please see my answer to this SO question to see an approximate walkthrough of Windows Forms DataBinding using the BindingSource class.

As for the tables per ComboBox strategy, this can be useful, as you can have a table per hierarchy. Here, we more likely discuss of an object-relational persistence strategy which can be a long way. In short, see this NHibernate Reference Documentation and the Chapter 8. Inheritence Mapping for further details. You will more likely be concerned by the Three Strategies.

Now I know, you make no mention of NHibernate, etc. in your question. My goal is to simply show you some of the most popular entity persistence strategies, which is asked indirectly by your your question.

Will Marcouiller
Don't forget BindingLists.
nportelli
@nportelli: You're right, a BindingList as much as an IList or IList<T> can both be used as DataSource.
Will Marcouiller