【问题标题】:How to change the name/string of an item in a ListBox?如何更改列表框中项目的名称/字符串?
【发布时间】:2012-11-22 20:02:00
【问题描述】:

以这种方式添加项目后:

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

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

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

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

【问题讨论】:

    标签: c# winforms listbox


    【解决方案1】:

    只是

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

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

    【讨论】:

    • 嗯,我确定这是我尝试的第一件事......我会再试一次,看看是否有我第一次没有正确输入的内容。谢谢!
    【解决方案2】:

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

    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);
    

    【讨论】:

    • 我猜这是Over Kill
    • 从索引中找到对象,然后将其传递给从传递的对象中找到索引并存储所选索引的函数,然后通过索引更新然后重新选择旧物品回来了? OP的问题比这简单多了!
    猜你喜欢
    • 2015-10-29
    • 2014-05-10
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多