ASP.NET TreeView shows old datasource

I do not know what's wrong in my code: The TreeView always shows the old data source, although I assign a new data source to it.

My purpose: To show XML in a tree view. Each leaf element is in "element_name = element_value" format:

name
|
+-- first = F1
|
+-- last = L1

Here is a sample code:

Add a TreeView control to Default.aspx:

<asp:TreeView ID="xmlTreeView" runat="server"
OnTreeNodeDataBound="XmlTreeView_OnTreeNodeDataBound"
ShowLines="True" EnableViewState="False">

In code behind:

public partial class _Default : System.Web.UI.Page
{
List<string> xmlStrList = new List<string>();

protected void Page_Load(object sender, EventArgs e)
{
// Initiate XML data
xmlStrList.Add("<name><first>F1</first><last>L1</last></name>");
xmlStrList.Add("<name><first>F2</first><last>L2</last></name>");
xmlStrList.Add("<name><first>F3</first><last>L3</last></name>");
xmlStrList.Add("<name><first>F4</first><last>L4</last></name>");

// Get random XML string
int i = DateTime.Now.Second % xmlStrList.Count;

// Create XmlDataSource
XmlDataSource dataSource = new XmlDataSource();
dataSource.Data = xmlStrList[i];

// Bind XMLDataSource to tree view
xmlTreeView.DataSource = dataSource;
xmlTreeView.DataBind();
}

// To show leaf element in "element_name = element_value" format
protected virtual void XmlTreeView_OnTreeNodeDataBound(Object sender, TreeNodeEventArgs e)
{
if (e.Node.DataItem is XmlElement)
{
XmlElement element = (XmlElement)e.Node.DataItem;
if (!element.FirstChild.HasChildNodes)
{
e.Node.Text = e.Node.Text + " = " + element.InnerText;
}
}
}
}

Everytime when I refresh the page, I get different XML string data source, but I see the SAME tree view data in browser! --- That is weird ...

I don't know why?

[Update] Copied from asp.net forum:
------------------------------------
This looks like a bug in the XmlDataSource control where modifying the Data property does not invalidate the cache. Setting EnableCaching=false is the workaround to use here.

Thanks,

Eilon
------------------------------------

1 comments:

Jun Meng said...

Copied from asp.net forum
According to Andrew:

The issue is that the XmlDataSource control has caching enabled by default, which is why you always see the same row getting bound (unless you rebuild the app or restart the web server). Just modify the XmlDataSource code as follows, and it will work (new code in bold):

XmlDataSource dataSource = new XmlDataSource();
dataSource.EnableCaching = false;
dataSource.Data = xmlStrList[i];

But: When the page is "refreshed", a NEW XmlDataSource is created. Why should we care about caching for the new XmlDataSource?