2

以这种方式添加项目后:

for (int x = 1; x <= 50; x++)
   {
      listBox1.Items.Add("Item " + x.ToString());
   }

我想知道如何在以后进行更改时更新他们的名字。在代码中。假设我想更改索引 5 处的项目名称,我该怎么做?

显然这样的事情是行不通的:

listBox1.Items[5].???? = "new string";
4

2 回答 2

4

只是

listBox1.Items[5] = "new string";

ListBox.ObjectCollection是实现的项目的集合IList。索引将给出项目本身。所以可以直接赋值。

于 2012-11-22T20:07:42.613 回答
1

您应该能够使用以下内容:

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);
于 2012-11-22T20:09:13.397 回答