Wednesday, September 14, 2005

the data that would not bind

Just encountered some really strange behavior with the databinding mechanism in .NET 1.1. So far, I haven't been able to determine what went wrong, although I was able to fix it. Those are the most unsettling of fixes; you keep trying things until something works, and when it works, you have no idea why. All I was trying to do was bind a System.Collections.ArrayList to a combo box and set the DisplayMember property of the combo to display the name of the item. So, something along these lines...

...
IList items = Model.GetItems();
combo.DataSource = items;
combo.DisplayMember = "Name";
...

public class Model {
...
public static IList GetItems() {
ArrayList items = new ArrayList();
// Create and add items that implement IMyInterface
return items;
}
}

public interface IMyInterface {
string Name {get;}
}


This code, when bound to the combo box, works just fine for the first item, and displays the Name property just as it should. However, every subsequent item instead ignores the DisplayMember property and spits out the result of item.ToString().

How did I fix it? In the Model.GetItems() method, instead of placing the items in an ArrayList, I created an IMyInterface[] array. Now it works like a charm, and I'm left wondering why.