Tuesday, November 2, 2010

ListBox Item Text Update (.NET C#)

ListBoxes are a convenient control that allows you toss any object into it and display the list of items to the user. You can override the ToString method to display your object name as you see fit. Unfortunately you cannot update the name of an item in the list by changing the variables related to your ToString override. I have seen a number of interesting approaches to the problem online. I created one of my own as it seemed like it might work. It looks a bit odd... but the reassignment of an item to itself triggers the necessary update to your text.


listBoxFiles.Items[listBoxFiles.SelectedIndex] = listBoxFiles.Items[listBoxFiles.SelectedIndex];


This is "uh" solution to the problem. I do not recommend it wholesale. It will work well if your ListBox is single selection and not sorted(see below on those). You should also evaluate the alternatives out in google land or wherever you find interesting solutions to annoying problems (back alleys, bingo parlors, or a bottle of alcohol). Plus you may run into some extra fun in the following situations:

Sorted ListBox
  • You are not "adding" items to the list box, just changing the array of items. You will need to set Sorted to false then true to trigger a proper sort.
  • ...and more... ?
Multi-Selection
  • Your selection will need to be carefully managed. The reassignment of multiple items in the array will likely break your selection state at the conclusion of the rename.
  • ...and more... ?

No comments:

Post a Comment