I'm using .NET with Windows Forms, but I believe there may be similar concerns with other toolkits.
Suppose we have a list of objects of a certain type. Using an example to make the following easier to read, suppose there is a
Category class to represent them. We display a list of them to allow a user to filter articles by category. Binding the ListBox component to a data source of
Category objects is a way to do so.
What would be the best way to add an entry labelled "All" in the same ListBox? Assume that it has to be in the list, and not as a separate option like a radio button.
I can think of the following approaches, but all of them seem to have a drawback.
- Create a "dummy"
Categoryinstance named "All" and an invalid ID.
This is the easiest way but it feels wrong conceptually, as "All" is not actually a category (no article belongs to a category named that). Also, depending on the framework the UI may not be allowed to create
- Don't use data binding at all; populate the list box with strings and use the selection's index to get the object from the data source.
This may beat the point of having data bound controls, and adds potential problems: What if we also want to add a "None" entry in the future? We'll have to increment the list box's selected index by 2 instead of 1 to get the correct object from the data source.
- Use an intermediate class,
CategoryListItem, to populate the list box with. It has a reference/pointer to a
nullfor dummy entries.
This one may be more elegant, but it adds the overhead of creating a new list of
CategoryListItem instances for every list of
Category instances we want to display.
Is one of the above a recommended way to data bind to such a component, or perhaps a way I haven't thought of?