2010-07-27 139 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

相关问题