2016-12-29 74 views
-4

我有一個列表框,其中項目是一個結構。該結構包含兩個字符串。一個用於標題,另一個用於純文本。現在我想更改列表框中現有項目中的文本。有沒有辦法做到這一點,而不刪除現有的並將更新版本添加到列表中?C#更改現有列表框項目中變量的值

這就是我想做的事情,

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

編譯器說,當我嘗試做這個「無法修改取消裝箱轉換的結果」。任何解決方案

結構,

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

對不起鄉親,我不知道這個網站是如何工作的

+0

你將要需要給我們一些代碼,以幫助您 –

+0

嗨,你可以檢查此鏈接要弄清楚它是如何工作的。 http://stackoverflow.com/help/how-to-ask,你需要幫助我們來幫助你。 –

+0

看看[這個](http://stackoverflow.com/questions/17280547/why-can-i-not-modify-the-result-of-an-unboxing-conversion) –

回答

0

請參考以下鏈接rename an item in listbox。我相信這會澄清一些事情。由於沒有提及改變文本的事件觸發器,我不會假定它。您可以通過全項迭代,並調用SelectedIndex的屬性來改變每個文本像這樣:

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

首先結構是值類型不引用類型。這意味着更改字段值的唯一方法是使用更改創建副本並替換從中複製的副本。所以,我會建議將它改爲一堂課。此外,由於列表框使用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中的項目和具有變化表明AA是更復雜一點。這裏有一個方法,它的工作原理:

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

如果我理解你正確地說,這些值存儲在「List test」中,而列表框只是一個可視表示。 – Bas

+0

對不起,我沒有完成打字,我無法編輯出於某種原因。 如果我理解正確,值存儲在「List 測試;」和列表框只是一個可視化表示。這並不是我想要這樣做的方式。我想將項目保存在列表框中。 – Bas

+0

將列表作爲數據源,列表框將把列表中的項目作爲對象存儲起來。它將通過使用ToString()方法來表示對象。通過綁定列表,您可以更改名稱和/或文本,並且更改將反映在列表框中。 – tinstaafl