xml attribure in dataset
I want to bind Repeater control to Dataset which is filled with XML data, but i don't know how to show attributes inside repeater.
Xml File:
<root>
<items>
<item id="9" name="111111111111" description="111111245" views="1" galleryID="0" />
</items>
</root>
Repeater code:
<asp:Repeater ID="rptrGalleries" runat="server">
<ItemTemplate>
<a href='Page?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'><%#DataBinder.Eval(Container.DataItem, "name") %></a>
</ItemTemplate>
</asp:Repeater>
Codebehind:
XDocument doc = XDocument.Load(Server.MapPath("~/xml/gallery.xml"));
IEnumerable<XElement> items = from item in doc.Descendants("item")
orderby Convert.ToDateTime(item.Attribute("lastChanges").Value) descending
where int.Parse(item.Attribute("galleryID").Value) == 0 && bool.Parse(item.Attribute("visible").Value) != false
select item;
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(doc.ToString()));
rptrGalleries.DataSource = ds;
rptrGalleries.DataBind();
When I compile site I receive this error:
System.Web.HttpExceptio开发者_运维问答n: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.
Create your repeater like so:
<asp:Repeater ID="rptTest" runat="server" OnItemDataBound="rptTest_ItemDataBound">
<ItemTemplate>
<asp:HyperLink ID="lnkTest" runat="server" />
</ItemTemplate>
</asp:Repeater>
Bind your repeater to the IEnumerable<XElements>
items object.
XDocument doc = XDocument.Load(Server.MapPath("~/xml/gallery.xml"));
IEnumerable<XElement> items = from item in doc.Descendants("item")
orderby Convert.ToDateTime(item.Attribute("lastChanges").Value) descending
where int.Parse(item.Attribute("galleryID").Value) == 0 && bool.Parse(item.Attribute("visible").Value) != false
select item;
rptTest.DataSource = items;
rptTest.DataBind();
And then Bind the data OnItemDataBound in the code behind like this:
void rptTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
XElement item = (XElement)e.Item.DataItem;
HyperLink lnkTest = (HyperLink)e.Item.FindControl("lnkTest");
lnkTest.NavigateUrl = "Page?id=" + item.Attribute("id").Value;
lnkTest.Text = item.Attribute("name").Value;
}
This is just how I would do it. I find that I have a lot more control in OnItemDataBound than trying to pass data directly to the ASP.Net Page.
精彩评论