添加/删除数据绑定列表框中的项目

时间:2010-07-27 23:52:25

标签: binding

我最近将一个xml文件存储到了一个列表框中。现在我想写一些函数来添加或删除该列表框中的项目。尝试listbox.items.add或listbox.items.insert:

时出现以下错误

使用ItemsControl.ItemsSource访问和修改元素。

我用谷歌搜索了它,并说它代之以“模型”,

但是我不知道该怎么做。那么如何在数据源中添加或删除项目?我不想将xml元素和值添加到原始文件中,然后将文件更新为数据源...

1 个答案:

答案 0 :(得分: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>

我没有编译或试图运行任何这些,但你应该得到一般的想法并使其适应你的代码。

相关问题