2010-07-27 135 views
1

我最近將一個xml文件綁定到一個列表框中。現在我想寫一些函數來添加或刪除列表框中的項目。嘗試listbox.items.add或listbox.items.insert時出現以下錯誤:從數據綁定列表框中添加/刪除項目

改爲使用ItemsControl.ItemsSource訪問和修改元素。

我GOOGLE了這一點,它說的「模式」,而不是工作,

但是我不知道該怎麼做。那麼我該如何在數據源中添加或刪除項目?我討厭不得不將xml元素和值添加到原始文件,然後更新文件作爲數據源...

回答

1

如何將XML加載到數據集中,然後操作數據集和重新綁定?

而不是使用XML文件,並綁定到列表框中,試試這個的:(source

string myXMLfile = "C:\\MySchema.xml"; 
    DataSet ds = new DataSet(); 
    try 
    { 
     //reads file and loads data into dataset 
     ds.ReadXml(myXMLfile); 
     //set the listbox's datasource to the dataset 
     //note that if you have complex XML then you might need to set this to one of the datatables in the datset to get what you want 
     listBox1.DataSource = ds; 
     listBox1.DataBind(); 
    } 
    catch (Exception ex) 
    { 
     //Handle error 
    } 

讓我們假設你的XML是相當簡單的。於牽引添加到DataSet,你會怎麼做:(source

//if customers is the name of your table (have not seen your XML) 
DataRow newCustomersRow = ds.Tables["Customers"].NewRow(); 

newCustomersRow["CustomerID"] = "ALFKI"; 
newCustomersRow["CompanyName"] = "Alfreds Futterkiste"; 

dataSet1.Tables["Customers"].Rows.Add(newCustomersRow); 

下面是應上述工作的XML例子:

<Data> 
    <Customers> 
    <Customer> 
     <CustomerID>123</CustomerID> 
     <CompanyName>Name</CompanyName> 
    </Customer> 
    </Customers> 
</Data> 

我還沒有編譯或試圖運行任何這個,但你應該得到一般的想法,並將其調整到你的代碼中。

+0

你能舉個例子嗎?數據源和數據集有什麼區別? 當前我綁定了一個文件,然後我爲listitems設置了綁定,以便框填滿。 – internetmw 2010-07-28 00:32:39

+0

數據源是您綁定到控件的數據源。在你的情況下,你正在使用xml文件作爲數據源並將該數據綁定到列表框。數據源是一個表示數據表的類,如果你綁定到一個列表框,我想你的XML也代表了這個數據表。我會用一個例子更新我的文章。 – kniemczak 2010-07-28 01:41:04

+0

而且這仍然可以用雙向數據綁定工作,所以我可以更新源文件? – internetmw 2010-07-28 12:13:49

相關問題