I have a tree view that I’m dynamically loading on the PageLoad event. Here is my tree view and data source:
<asp:TreeView ID="tv" runat="server" DataSourceID="xds"
SelectedNodeStyle-ForeColor="Red" NodeStyle-ForeColor="Black">
<DataBindings>
<asp:TreeNodeBinding DataMember="Node"
ValueField="Id" TextField="Title" />
</DataBindings>
</asp:TreeView>
<asp:XmlDataSource ID="xds" runat="server" EnableCaching="false" />
This is the code I run on PageLoad
StringBuilder sb = new StringBuilder();
XmlWriter xw = XmlWriter.Create(sb);
WriteTreeViewXml(xw);
xw.Flush();
xw.Close();
xds.Data = sb.ToString();
xds.DataBind();
tv.Nodes[0].Selected = true; // error here
This works fine, the tree view gets loaded correctly. Now I’m trying to add styling to the SelectedNode. This works when I click on a specific node, but the root node isn’t styled when the page loads. So I’m trying to set the root node to selected on PageLoad
I get this error when I try to set the root node as selected:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
For some reason the tree view is empty after I bind the data source.
Does anyone know how I can do this?
You need to call tv.Databind() after the line that calls xds.DataBind(); Otherwise the control isn’t being bound to the datasource. I believe it would do this for you if you were declaratively setting the XmlDataSource (to a static file, for example), but since you are manually populating it, you’ll need to manually call the control’s DataBind method as well.