An app I am currently working on uses the paradigm of moving items from one listbox to another instead of doing a DB call for each user interaction.
I needed a way to nicely move stuff from left to right and right to left and keep it sorted. By using Generics I found a quick way to sort the data and rebind it to the control. What I ended up with looks something like this:
protected void MoveEntryFromSourceToTarget(ListBox source, ListBox target, string itemText, string itemID)
{
DeleteEntryInList(source, itemText);
AddEntryToList(target, itemText, itemID);
}
protected void DeleteEntryInList(ListBox target, string targetText)
{
ListItem myItem = target.Items.FindByText(targetText);
target.Items.Remove(myItem);
}
protected void AddEntryToList(ListBox target, string itemText, string itemID)
{
ListItem myNewItem = new ListItem(itemText, itemID);
target.Items.Add(myNewItem);
SortedDictionary<string, string> myList = new SortedDictionary<string, string>();
foreach (ListItem myItem in target.Items)
{
// since this sorts on key and not value, put the text in the key spot...
myList.Add(myItem.Text, myItem.Value);
}
target.Items.Clear();
foreach (KeyValuePair<string, string> kvp in myList)
{
// Remember that the key/value is really value/key...
target.Items.Add(new ListItem(kvp.Key, kvp.Value));
}
}