Making an Adapter
It may be a little difficult to remember to use the Items collection of the list box for some operations but not for others. For this reason, we might prefer to have a class that hides some of these complexities and adapts the interface to the simpler one we wish we had, rather like the ListBox interface in VB6. We'll create a simpler interface in a ListAdapter class that then operates on an instance of the ListBox class.
public class ListAdapter { private ListBox listbox; //operates on this one public ListAdapter(ListBox lb) { listbox = lb; } //----- public void Add(string s) { listbox.Items.Add (s); } //----- public int SelectedIndex() { return listbox.SelectedIndex; } //----- public void Clear() { listbox.Items.Clear (); } //----- public void clearSelection() { int i = SelectedIndex(); if(i >= 0) { listbox.SelectedIndex =-1; } } }
Then we can make our program a little simpler.
private void btClone_Click(object sender, EventArgs e) { int i = lskids.SelectedIndex (); if( i >= 0) { Swimmer sw = swdata.getSwimmer (i); lsnewKids.Add (sw.getName() + "\t" + sw.getTime ()); lskids.clearSelection (); } }
Now let's recognize that if we are always adding swimmers and times spaced apart like this, maybe there should be a method in our ListAdapter that handles the Swimmer object directly.
public void Add(Swimmer sw) { listbox.Items.Add (sw.getName() + "" + sw.getTime()); }
This simplifies the Click Event handler even more.
private void btClone_Click(object sender, EventArgs e) { int i = lskids.SelectedIndex (); if( i >= 0) { Swimmer sw = swdata.getSwimmer (i); lsnewKids.Add (sw); lskids.clearSelection (); } }
What we have done is create an Adapter class that contains a ListBox class and simplifies how you use the ListBox. Next, we'll see how we can use the same approach to create adapters for two of the more complex visual controls.