The main code is as follows:
- <HTML>
- <Head>
- </Head>
- <Body>
- <Form ID = "form1" runat = "server">
- <Div>
- <Asp: treeviewrunat = "server" expandimageurl = "images/closed.gif"
- Collapseimageurl = "images/open.gif"
- Ontreenodepopulate = "node_populate" id = "tvwauthors">
- <Nodes>
- <Asp: treenodetext = "Authors" populateondemand = true
- Value = "0"/>
- </Nodes>
- </ASP: Treeview>
- </Div>
- </Form>
- </Body>
- </Html>
Background code:
- Void node_populate (objectsender, system. Web. UI. webcontrols. treenodeeventargs E)
- {
- If (E. node. childnodes. Count = 0)
- {
- Switch (E. node. Depth)
- {
- Case 0:
- Fillauthors (E. node );
- Break;
- Case 1:
- Filltitlesforauthors (E. node );
- Break;
- }
- }
- }
- Void fillauthors (treenode node)
- {
- String connstring = system. configuration. configurationsettings.
- Connectionstrings ["northwindconnnection"]. connectionstring;
- Sqlconnection connection = new sqlconnection (connstring );
- Sqlcommand command = new sqlcommand ("select * from
- Authors ", connection );
- Sqldataadapter adapter = new sqldataadapter (command );
- Dataset authors = new dataset ();
- Adapter. Fill (authors );
- If (authors. Tables. Count> 0)
- {
- Foreach (datarow row in authors. Tables [0]. Rows)
- {
- Treenode newnode = new
- Treenode (row ["au_fname"]. tostring () + "" +
- Row ["au_lname"]. tostring (),
- Row ["au_id"]. tostring ());
- Newnode. populateondemand = true; // whether to dynamically fill nodes
- Newnode. selectaction = treenodeselectaction. Expand; // events triggered when a node is selected (switching the expand and collapse statuses of nodes .)
- Node. childnodes. Add (newnode );
- }
- }
- }
- Void filltitlesforauthors (treenode node)
- {
- String authorid = node. value;
- String connstring = system. configuration. configurationsettings.
- Connectionstrings ["northwindconnnection"]. connectionstring;
- Sqlconnection connection = new sqlconnection (connstring );
- Sqlcommand command = new sqlcommand ("select T. title,
- T. title_id from titles t "+
- "Inner join titleauthor Ta on
- T. title_id = TA. title_id "+
- "Where ta. au_id = '" + authorid + "'", connection );
- Sqldataadapter adapter = new sqldataadapter (command );
- Dataset titlesforauthors = new dataset ();
- Adapter. Fill (titlesforauthors );
- If (titlesforauthors. Tables. Count> 0)
- {
- Foreach (datarow row in titlesforauthors. Tables [0]. Rows)
- {
- Treenode newnode = new treenode (
- Row ["title"]. tostring (), row ["title_id"]. tostring ());
- Newnode. populateondemand = false; // whether to dynamically fill the node
- Newnode. selectaction = treenodeselectaction. None;
- Node. childnodes. Add (newnode );
- }
- }
- }