I want to rename selected item in listbox. How to I can do this? Thanks.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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";
回答2:
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.