Reputation: 18859
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?
Upvotes: 0
Views: 870
Reputation: 1434
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.
Upvotes: 1
Reputation: 13706
The data doesn't exist until the control's DataBinding
event has been run, which may or may not happen during the Load
event. You should put any code which requires the data/nodes to exist into the DataBound
event for the control. See this documentation:
DataBound
Raised at the end of data-binding operations in a data-bound control. In a GridView control, data binding is complete for all rows and any child controls.
Use this event to format data-bound content or to initiate data binding in other controls that depend on values from the current control's content. (For more information, see Catch-Up Events for Added Controls earlier in this topic.)
Upvotes: 1