C#更改现有列表框项

时间:2016-12-29 15:15:25

标签: c# listbox

我有一个列表框,其中的项目是结构。该结构包含两个字符串。一个用于标题,另一个用于纯文本。现在我想更改列表框中现有项目中的文本。有没有办法在不删除现有内容并将更新后的版本添加到列表的情况下执行此操作?

这就是我想做的事,

((TextItemRecord) listbox1.Items[myListbox1.BeforeIndex]).text = "Blablabla";

编译器说,"无法修改取消装箱转换的结果"当我尝试这样做。任何解决方案?

STRUCT,

struct TextItemRecord
{
    public UInt64 address;
    public string name, text;

    public TextItemRecord(UInt64 address, string name)
    {
        this.address = address;
        this.name = name;
        this.text = "";
    }
    public override string ToString()
    {
        return name;
    }
}

我很抱歉,我不知道这个网站应该如何运作

2 个答案:

答案 0 :(得分:0)

请参阅以下链接rename an item in listbox。我相信这会清除一些事情。由于没有提到改变文本的事件触发器,我不会假设它。您可以遍历所有项目并调用SelectedIndex属性来更改每个文本,如下所示:

   foreach(var item in listbox1)
        listbox1.Items[item.SelectedIndex] = "Blablabla";

答案 1 :(得分:0)

首先关闭结构是值类型而不是引用类型。这意味着更改字段值的唯一方法是创建包含更改的副本并替换您从中复制的副本。所以,我建议把它改成一个班级。此外,由于ListBox使用ToString()方法显示项目,我建议更改它以允许显示text字段:

class TextItemRecord
{
    public UInt64 address;
    public string name;
    public string text;

    public TextItemRecord(UInt64 address, string name)
    {
        this.address = address;
        this.name = name;
        this.text = "";
    }
    public override string ToString()
    {
        return $"{name} - {text}";
    }
}

现在,要显示列表框中的项目列表,请将DataSource属性分配给列表:

List<TextItemRecord> test;
public Form1()
{
    InitializeComponent();

    test = new List<TextItemRecord>()
    {
        new TextItemRecord(1234, "AAA"),
        new TextItemRecord(5678, "BBB"),
        new TextItemRecord(9012, "CCC")
    };
    listBox1.DataSource = test;
}

修改ListBox中的项目并显示更改有点复杂。这是一种有效的方法:

private void AddText(List<TextItemRecord> tirList, int index, string text)
{
    BindingManagerBase bmb = listBox1.BindingContext[test];
    bmb.SuspendBinding();
    test[index].text = text;
    bmb.ResumeBinding();
}