XmlDataSources, DataItem and the sealed XmlDataSourceNodeDescriptor

One way of getting to the DataItem in ItemDataBound when binding to an XmlDataSource is by using the DataBinder.Eval method like so:

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) {

    Trace.Write(e.Item.DataItem.GetType().ToString());

    string employeeName = DataBinder.Eval(e.Item.DataItem, "Name") as string; //Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Name"))

 

}

e.Item.DataItem is of Type System.Web.UI.WebControls.XmlDataSourceNodeDescriptor which is sealed :-(

Comments from Matt Hawley

Actually, XmlDataSourceNodeDescriptor implements IXPathNavigable, which allows you to create an XPathNavigator. See the following...

Label lbl = (Label) e.Item.FindControl("lbl");
XPathNavigator nav = ((IXPathNavigable) e.Item.DataItem).CreateNavigator();

XPathNodeIterator it = nav.Select("./name");
it.MoveNext();
lbl.Text = it.Current.Value;


Comments from Oleg

IMHO, The right way to get DataItem value is to use the XPathBinder class. The Matt's sample will be looks like:

Label lbl = (Label) e.Item.FindControl("lbl");

IEnumerator er = XPathBinder.Select(e.Item.DataItem, "./name").GetEnumerator();

er.MoveNext();
lbl.Text = ((XmlElement)er.Current).Value;

or it can be simple bound with Eval method:
lbl.Text = XPathBinder.Eval(e.Item.DataItem, "./name", "");

 

1 Comment

  • Thanks Oleg

    It took me ages to find such a simple solution...

    lbl.Text = XPathBinder.Eval(e.Item.DataItem, "./name", "");

    What a star

Comments have been disabled for this content.