例如,我有一个带有BookDetails的xml文件,我将它显示在GridView表单上。现在我想为GridView提供添加,编辑,删除选项。当我们从SQL数据源使用DataBinding时,我知道如何为gridview添加,编辑和删除选项,但在这里我们应该将数据存储到现有的xml文件中。
包含数据的Xml文件:
<books>
<book>
<title>CLR via C#</title>
<isbn>0735667454</isbn>
<author>Jeffrey Richter</author>
</book>
<book>
<title>Pro C# 5.0 and the .NET 4.5 Framework</title>
<isbn>1430242337</isbn>
<author>Andrew Troelsen</author>
</book>
<book>
<title>Building Windows 8 Apps with C# and XAML</title>
<isbn>0321822161</isbn>
<author>Jeremy Likness</author>
</book>
</books>
ASP.NET代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Book Store</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvBooks" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bindXml();
}
private void bindXml()
{
//Create a DataSet
DataSet ds = new DataSet();
//Load the XML data into the DataSet
ds.ReadXml(Server.MapPath("books.xml"));
//Bind the DataSet to the GridView control
gvBooks.DataSource = ds;
gvBooks.DataBind();
}
}