5

I want to rename selected item in listbox. How to I can do this? Thanks.

Tavousi
  • 14,848
  • 18
  • 51
  • 70

2 Answers2

5

Edit: Revisiting this quite a few years later; below are the ways you can do this dependent on the UI framework you are using. This carries the assumption that you'd like to change the selected text.

ASP.Net WebForms

protected void ChangeListBoxSelectedItemText(string textToChangeTo)
{
    lstBoxExample.SelectedItem.Text = textToChangeTo;
}

WPF - Assuming the ListBox contains Label objects

// To achieve this in WPF you have to cast the object
// This is because a ListBox can contain numerous types of UI objects
var selectedLabel = (Label)lstBoxExample.SelectedItem;
selectedLabel.Content = "Text to change to";

WinForms

// There may very well be a better way to do this
lstBoxExample.Items[lstBoxExample.SelectedIndex] = "New Item";
Luke Merrett
  • 5,724
  • 8
  • 38
  • 70
  • The type of `ListBox.SelectedItem` is `Object`. Last time I checked, `System.Object` didn't have a Text member. True for both `System.Windows.Forms.ListBox` (WinForms) and `System.Windows.Controls.ListBox` (WPF). – Tergiver Dec 18 '10 at 20:43
  • 2
    Ah, which just goes to show how important it is to specify which UI framework you are using. You simply got lucky and they happen to be using ASP.Net because as I already said, it's not true for WinForms or WPF. – Tergiver Dec 19 '10 at 15:53
  • `.Text` is not in my listbox, as indicated by prior comments – barlop Jun 23 '15 at 16:29
  • @Tergiver revisiting this many years later! You were indeed right the UI framework was not specified, I've updated the answer to give WebForms, WPF and WinForms examples. Hopefully this helps anyone else who comes across this in the future. – Luke Merrett Jun 23 '15 at 20:37
1

ListBox contains objects. Exactly what do you mean by "renaming" an item?

If what you want is to change the text that is displayed on the list, what you have to do is change the object so that its ToString method will return the desired text.

Most commonly, you are probably storing strings in the ListBox, and in that case in order to "rename" an item, you have to remove the old item and insert the new text in the same index.

Ran
  • 5,989
  • 1
  • 24
  • 26