下面的代码演示了如何利用Linq结合AspNetPager控件实现分页功能,以及如果利用Linq to Xml将当前页数据保存为Xml
using (NorthWindDataContext db = new NorthWindDataContext())
{
int Page = Utils.GetPageIndex();//取得当前页码
var s = from c in db.T_Tests orderby c.F_AutoId select new { c.F_ID,F_AutoID = c.F_AutoId.ToString().PadLeft(8,'0')};
var p = s.Skip((Page - 1) * this.AspNetPager1.PageSize).Take(this.AspNetPager1.PageSize);//取得当前页数据(注:先跳过(Page-1)*PageSize条记录后,再取PageSize条记录)
this.GridView3.DataSource = p;
this.GridView3.DataBind();
this.AspNetPager1.RecordCount = s.Count();//设置分页控件的总记录数
this.AspNetPager1.CurrentPageIndex = Page;//设置分页控件的当前页
//将当前数据保存为xml
XDocument doc = new XDocument(new XElement(
"T_Test", from d in p
select
(
new XElement
(
"data",
new XAttribute("F_ID", d.F_ID),
new XAttribute("F_AutoID", d.F_AutoID)
)
)
)
);
doc.Save("c:\\demo.xml");
db.Dispose();//及时释放资源
}
保存的Demo.Xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<T_Test>
<data F_ID="9552e4dc-9a0a-414e-ab80-b0252f88411e" F_AutoID="00000014" />
<data F_ID="2d135009-d24f-46ca-92ba-6d7b706f4025" F_AutoID="00000015" />
<data F_ID="2e725756-da8c-4ede-ba13-00aa91fbd8e2" F_AutoID="00000016" />
<data F_ID="d6a1b0aa-40e8-4cf8-a3f2-c1c28576d6f3" F_AutoID="00000017" />
<data F_ID="fed11493-6349-419e-a83b-c42f6d318735" F_AutoID="00000018" />
<data F_ID="c1eedd2b-2d92-46e3-8aab-f4180e106c6f" F_AutoID="00000019" />
<data F_ID="762a57b5-8ca6-4d8c-9569-bbd62d4873a6" F_AutoID="00000020" />
<data F_ID="a468b3b0-1392-4bf5-be84-b2e1a90c53de" F_AutoID="00000021" />
<data F_ID="d3526eff-23d4-41a4-b6b2-d4b1f5bf6085" F_AutoID="00000022" />
<data F_ID="6e0687ea-07be-4a83-a50f-4d3700868d15" F_AutoID="00000023" />
<data F_ID="f343f96f-8d2b-4ef5-a431-82df7f607d6e" F_AutoID="00000024" />
<data F_ID="34d7d945-599c-4986-bdec-2ee7bf338e0f" F_AutoID="00000025" />
<data F_ID="2c569843-ecfd-4f53-a59b-5e28083ed4e3" F_AutoID="00000026" />
</T_Test>