例如,我有一个带有 BookDetails 的 xml 文件,并将其显示在 GridView 表单上。现在我想为 GridView 提供添加、编辑、删除选项。当我们使用 DataBinding 从 SQL 数据源访问时,我知道如何为 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();
}
}