添加项目这种方式后:如何更改ListBox中项目的名称/字符串?
for (int x = 1; x <= 50; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
我不知道我怎么能在以后更新自己的名字时更改。在代码中。假设我想更改索引5处的项目名称,那么我该怎么做?
显然,这样的事情是行不通的:
listBox1.Items[5].???? = "new string";
添加项目这种方式后:如何更改ListBox中项目的名称/字符串?
for (int x = 1; x <= 50; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
我不知道我怎么能在以后更新自己的名字时更改。在代码中。假设我想更改索引5处的项目名称,那么我该怎么做?
显然,这样的事情是行不通的:
listBox1.Items[5].???? = "new string";
您应该能够使用以下命令:
private void UpdateListBoxItem(ListBox lb, object item) {
int index = lb.Items.IndexOf(item);
int currIndex = lb.SelectedIndex;
lb.BeginUpdate();
try {
lb.ClearSelected();
lb.Items[index] = item;
lb.SelectedIndex = currIndex;
}
finally {
lb.EndUpdate();
}
}
这是用法:
MyObject item = (MyObject)myListBox.Items[0];
item.Text = "New value";
UpdateListBoxItem(myListBox, item);
只是
listBox1.Items[5] = "new string";
的ListBox.ObjectCollection
是实现IList
项目的集合。索引会给物品本身。所以你可以直接分配它。
嗯,我确信这是我想的第一件事......我会努力再看看有没有我第一次输入正确的东西。谢谢! – TheScholar
@TheScholar你应该接受最有帮助的答案(如果有的话),点击每个答案左上角的绿色勾号。这就是如何工作.. – nawfal
这是'Over Kill'我猜 –
从索引中找到对象,然后将它传递给函数,该函数从传递的对象中找回索引并存储选定的索引,然后通过索引更新,然后重新选择旧的项目? OP的问题比所有的要简单得多! – nawfal
非常感谢您的帮助03Usr ^^ – TheScholar