The other day I was writing some code and I got an error message. It happened to be one of those cases where it should have worked. You know when good code it written it just happens to work like you expect it to. The general idea was:
Private Sub FillCombos()
Dim dict As New Dictionary(Of String, String)
With dict
.Add("Steve", "Steve Harris")
.Add("Bill", "Bill Murray")
.Add("Dave", "Dave's not here")
.Add("Jack", " (Captain) Jack Sparrow")
End With
ComboBox1.DataSource = dict.Keys
ComboBox2.DataSource = dict.Values
End Sub
Seems pretty logical. The Keys property of a dictionary is a collection and so is the Values. A collection is just a list of things. They should be bindable, right? Well, no. The error you get is: “Complex DataBinding accepts as a data source either an IList or an IListSource.” And after poking around, it’s right. The collections do not implement those interfaces.
So that was going to be a blog topic about how and why those collections couldn’t be databound, but when I tried it on my other computer, I noticed that I had extra methods on those collections, ToArray being one of them. so I used ToArray and the databinding worked. As it turns out, the ToArray was added from System.Linq.Enumerable, which comes along with .NET 3.0. I switched the project to .NET 2.0 and the ToArray function disappeared.
So now, I’m blogging more about the blunt realization that I’m officially missing out on additional functionality that would have simplified my code. Well, as complicated as this solution makes it:
ComboBox1.DataSource = New Generic.List(Of String)(dict.Keys)
ComboBox2.DataSource = New Generic.List(Of String)(dict.Values)
So, with the release of Windows 7, I do plan on installing VS 2008 at work and driving ahead with 64-bit development under .NET 3.5. Well, eventually. There’s still some Win2k workstations out there…