この方法でアイテムを追加した後:
for (int x = 1; x <= 50; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
変更が加えられたときに、後で名前を更新する方法を考えています。コードで。インデックス 5 の項目の名前を変更したいとしましょう。どうすればよいでしょうか?
明らかに、そのようなものは機能しません:
listBox1.Items[5].???? = "new string";
ただ
listBox1.Items[5] = "new string";
ListBox.ObjectCollectionを実装するアイテムのコレクションですIList。アイテム自体を与える索引付け。したがって、直接割り当てることができます。
次のものを使用できるはずです。
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);