File: TreeView.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (3517 lines) | stat: -rw-r--r-- 145,120 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
//------------------------------------------------------------------------------
// <copyright file="TreeView.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Globalization;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.Util;


    /// <devdoc>
    ///     Provides a tree view control
    /// </devdoc>
    [ControlValueProperty("SelectedValue")]
    [DefaultEvent("SelectedNodeChanged")]
    [Designer("System.Web.UI.Design.WebControls.TreeViewDesigner, " + AssemblyRef.SystemDesign)]
    [SupportsEventValidation]
    public class TreeView : HierarchicalDataBoundControl, IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler {
        private static string populateNodeScript = @"
    function TreeView_PopulateNodeDoCallBack(context,param) {
        ";
        private static string populateNodeScriptEnd = @";
    }
";

        internal const int RootImageIndex = 0;
        internal const int ParentImageIndex = 1;
        internal const int LeafImageIndex = 2;

        internal const int NoExpandImageIndex = 3;
        internal const int PlusImageIndex = 4;
        internal const int MinusImageIndex = 5;

        internal const int IImageIndex = 6;

        internal const int RImageIndex = 7;
        internal const int RPlusImageIndex = 8;
        internal const int RMinusImageIndex = 9;

        internal const int TImageIndex = 10;
        internal const int TPlusImageIndex = 11;
        internal const int TMinusImageIndex = 12;

        internal const int LImageIndex = 13;
        internal const int LPlusImageIndex = 14;
        internal const int LMinusImageIndex = 15;

        internal const int DashImageIndex = 16;
        internal const int DashPlusImageIndex = 17;
        internal const int DashMinusImageIndex = 18;

        internal const int ImageUrlsCount = 19;

        // Also used by Menu
        internal const char InternalPathSeparator = '\\';
        private const char EscapeCharacter = '|';
        private const string EscapeSequenceForPathSeparator = "*|*";
        private const string EscapeSequenceForEscapeCharacter = "||";

        private string[] _imageUrls;
        private string[] _levelImageUrls;

        private static readonly object CheckChangedEvent = new object();
        private static readonly object SelectedNodeChangedEvent = new object();
        private static readonly object TreeNodeCollapsedEvent = new object();
        private static readonly object TreeNodeExpandedEvent = new object();
        private static readonly object TreeNodePopulateEvent = new object();
        private static readonly object TreeNodeDataBoundEvent = new object();

        private TreeNodeStyle _nodeStyle;
        private TreeNodeStyle _rootNodeStyle;
        private TreeNodeStyle _parentNodeStyle;
        private TreeNodeStyle _leafNodeStyle;
        private TreeNodeStyle _selectedNodeStyle;
        private Style _hoverNodeStyle;
        private HyperLinkStyle _hoverNodeHyperLinkStyle;

        private Style _baseNodeStyle;

        // Cached styles. In the current implementation, the styles are the same for all items
        // and submenus at a given depth.
        private List<TreeNodeStyle> _cachedParentNodeStyles;
        private List<string> _cachedParentNodeClassNames;
        private List<string> _cachedParentNodeHyperLinkClassNames;
        private List<TreeNodeStyle> _cachedLeafNodeStyles;
        private List<string> _cachedLeafNodeClassNames;
        private List<string> _cachedLeafNodeHyperLinkClassNames;
        private Collection<int> _cachedLevelsContainingCssClass;

        private TreeNode _rootNode;
        private TreeNode _selectedNode;

        private TreeNodeCollection _checkedNodes;

        private TreeNodeStyleCollection _levelStyles;

        private ArrayList _checkedChangedNodes;

        private TreeNodeBindingCollection _bindings;

        private int _cssStyleIndex;

        // 
        private bool _loadingNodeState;
        private bool _dataBound;
        private bool _accessKeyRendered;

        private bool _isNotIE;
        private bool _renderClientScript;

        private bool _fireSelectedNodeChanged;

        private string _cachedExpandImageUrl;
        private string _cachedCollapseImageUrl;
        private string _cachedNoExpandImageUrl;
        private string _cachedClientDataObjectID;
        private string _cachedExpandStateID;
        private string _cachedImageArrayID;
        private string _cachedPopulateLogID;
        private string _cachedSelectedNodeFieldID;

        private string _currentSiteMapNodeDataPath;

        private string _callbackEventArgument;

        internal bool AccessKeyRendered {
            get {
                return _accessKeyRendered;
            }
            set {
                _accessKeyRendered = value;
            }
        }

        private List<string> CachedLeafNodeClassNames {
            get {
                if (_cachedLeafNodeClassNames == null) {
                    _cachedLeafNodeClassNames = new List<string>();
                }
                return _cachedLeafNodeClassNames;
            }
        }

        private List<TreeNodeStyle> CachedLeafNodeStyles {
            get {
                if (_cachedLeafNodeStyles == null) {
                    _cachedLeafNodeStyles = new List<TreeNodeStyle>();
                }
                return _cachedLeafNodeStyles;
            }
        }

        private List<string> CachedLeafNodeHyperLinkClassNames {
            get {
                if (_cachedLeafNodeHyperLinkClassNames == null) {
                    _cachedLeafNodeHyperLinkClassNames = new List<string>();
                }
                return _cachedLeafNodeHyperLinkClassNames;
            }
        }

        private Collection<int> CachedLevelsContainingCssClass {
            get {
                if (_cachedLevelsContainingCssClass == null) {
                    _cachedLevelsContainingCssClass = new Collection<int>();
                }
                return _cachedLevelsContainingCssClass;
            }
        }

        private List<TreeNodeStyle> CachedParentNodeStyles {
            get {
                if (_cachedParentNodeStyles == null) {
                    _cachedParentNodeStyles = new List<TreeNodeStyle>();
                }
                return _cachedParentNodeStyles;
            }
        }

        private List<string> CachedParentNodeClassNames {
            get {
                if (_cachedParentNodeClassNames == null) {
                    _cachedParentNodeClassNames = new List<string>();
                }
                return _cachedParentNodeClassNames;
            }
        }

        private List<string> CachedParentNodeHyperLinkClassNames {
            get {
                if (_cachedParentNodeHyperLinkClassNames == null) {
                    _cachedParentNodeHyperLinkClassNames = new List<string>();
                }
                return _cachedParentNodeHyperLinkClassNames;
            }
        }


        /// <devdoc>
        /// Gets and sets whether the tree view will automatically bind to data
        /// </devdoc>
        [
        DefaultValue(true),
        WebCategory("Behavior"),
        WebSysDescription(SR.TreeView_AutoGenerateDataBindings)
        ]
        public bool AutoGenerateDataBindings {
            get {
                object o = ViewState["AutoGenerateDataBindings"];
                if (o == null) {
                    return true;
                }
                return (bool)o;
            }
            set {
                ViewState["AutoGenerateDataBindings"] = value;
            }
        }


        /// <devdoc>
        ///     Gets the tree level data mappings
        /// </devdoc>
        [
        DefaultValue(null),
        MergableProperty(false),
        Editor("System.Web.UI.Design.WebControls.TreeViewBindingsEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebCategory("Data"),
        WebSysDescription(SR.TreeView_DataBindings)
        ]
        public TreeNodeBindingCollection DataBindings {
            get {
                if (_bindings == null) {
                    _bindings = new TreeNodeBindingCollection();
                    if (IsTrackingViewState) {
                        ((IStateManager)_bindings).TrackViewState();
                    }
                }
                return _bindings;
            }
        }


        /// <devdoc>
        ///     Gets the currently checked nodes in tree
        /// </devdoc>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public TreeNodeCollection CheckedNodes {
            get {
                if (_checkedNodes == null) {
                    _checkedNodes = new TreeNodeCollection(null, false);
                }
                return _checkedNodes;
            }
        }

        private ArrayList CheckedChangedNodes {
            get {
                if (_checkedChangedNodes == null) {
                    _checkedChangedNodes = new ArrayList();
                }
                return _checkedChangedNodes;
            }
        }

        /// <devdoc>
        ///     Gets the hidden field ID for the expand state of this TreeView
        /// </devdoc>
        internal string ClientDataObjectID {
            get {
                if (_cachedClientDataObjectID == null) {
                    _cachedClientDataObjectID = ClientID + "_Data";
                }
                return _cachedClientDataObjectID;
            }
        }


        /// <devdoc>
        ///     Gets and sets the image ToolTip for the collapse node icon (minus).
        /// </devdoc>
        [Localizable(true)]
        [WebSysDefaultValue(SR.TreeView_CollapseImageToolTipDefaultValue)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_CollapseImageToolTip)]
        public string CollapseImageToolTip {
            get {
                string s = (string)ViewState["CollapseImageToolTip"];

                if (s == null) {
                    return SR.GetString(SR.TreeView_CollapseImageToolTipDefaultValue);
                }

                return s;
            }
            set {
                ViewState["CollapseImageToolTip"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets the image url for the collapse node icon (minus).
        /// </devdoc>
        [DefaultValue("")]
        [Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
        [UrlProperty()]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_CollapseImageUrl)]
        public string CollapseImageUrl {
            get {
                string s = (string)ViewState["CollapseImageUrl"];
                if (s == null) {
                    return String.Empty;
                }
                return s;
            }
            set {
                ViewState["CollapseImageUrl"] = value;
            }
        }

        internal string CollapseImageUrlInternal {
            get {
                if (_cachedCollapseImageUrl == null) {
                    switch (ImageSet) {
                        case TreeViewImageSet.Arrows: {
                                _cachedCollapseImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Arrows_Collapse.gif");
                                break;
                            }
                        case TreeViewImageSet.Contacts: {
                                _cachedCollapseImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Contacts_Collapse.gif");
                                break;
                            }
                        case TreeViewImageSet.XPFileExplorer: {
                                _cachedCollapseImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_XP_Explorer_Collapse.gif");
                                break;
                            }
                        case TreeViewImageSet.Msdn: {
                                _cachedCollapseImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_MSDN_Collapse.gif");
                                break;
                            }
                        case TreeViewImageSet.WindowsHelp: {
                                _cachedCollapseImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Windows_Help_Collapse.gif");
                                break;
                            }
                        case TreeViewImageSet.Custom: {
                                _cachedCollapseImageUrl = CollapseImageUrl;
                                break;
                            }
                        default: {
                                _cachedCollapseImageUrl = String.Empty;
                                break;
                            }
                    }
                }
                return _cachedCollapseImageUrl;
            }
        }

        internal bool CustomExpandCollapseHandlerExists {
            get {
                TreeNodeEventHandler collapseHandler = (TreeNodeEventHandler)Events[TreeNodeCollapsedEvent];
                TreeNodeEventHandler expandHandler = (TreeNodeEventHandler)Events[TreeNodeExpandedEvent];
                return ((collapseHandler != null) || (expandHandler != null));
            }
        }


        /// <devdoc>
        ///     Gets and sets whether the control should try to use client script, if the browser is capable.
        /// </devdoc>
        [DefaultValue(true)]
        [WebCategory("Behavior")]
        [Themeable(false)]
        [WebSysDescription(SR.TreeView_EnableClientScript)]
        public bool EnableClientScript {
            get {
                object o = ViewState["EnableClientScript"];
                if (o == null) {
                    return true;
                }

                return (bool)o;
            }
            set {
                ViewState["EnableClientScript"] = value;
            }
        }

        /// <devdoc>
        ///     Gets whether hover styles have been enabled (set)
        /// </devdoc>
        internal bool EnableHover {
            get {
                return (Page != null &&
                    (Page.SupportsStyleSheets || Page.IsCallback ||
                    (Page.ScriptManager != null && Page.ScriptManager.IsInAsyncPostBack)) &&
                    RenderClientScript &&
                    (_hoverNodeStyle != null));
            }
        }

        [DefaultValue(-1)]
        [TypeConverter(typeof(TreeViewExpandDepthConverter))]
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_ExpandDepth)]
        public int ExpandDepth {
            get {
                object o = ViewState["ExpandDepth"];
                if (o == null) {
                    return -1;
                }
                return (int)o;
            }
            set {
                ViewState["ExpandDepth"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets the image ToolTip for the Expand node icon (minus).
        /// </devdoc>
        [Localizable(true)]
        [WebSysDefaultValue(SR.TreeView_ExpandImageToolTipDefaultValue)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_ExpandImageToolTip)]
        public string ExpandImageToolTip {
            get {
                string s = (string)ViewState["ExpandImageToolTip"];

                if (s == null) {
                    return SR.GetString(SR.TreeView_ExpandImageToolTipDefaultValue);
                }

                return s;
            }
            set {
                ViewState["ExpandImageToolTip"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets the image url for the expand node icon (plus).
        /// </devdoc>
        [DefaultValue("")]
        [Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
        [UrlProperty()]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_ExpandImageUrl)]
        public string ExpandImageUrl {
            get {
                string s = (string)ViewState["ExpandImageUrl"];
                if (s == null) {
                    return String.Empty;
                }
                return s;
            }
            set {
                ViewState["ExpandImageUrl"] = value;
            }
        }

        internal string ExpandImageUrlInternal {
            get {
                if (_cachedExpandImageUrl == null) {
                    switch (ImageSet) {
                        case TreeViewImageSet.Arrows: {
                                _cachedExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Arrows_Expand.gif");
                                break;
                            }
                        case TreeViewImageSet.Contacts: {
                                _cachedExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Contacts_Expand.gif");
                                break;
                            }
                        case TreeViewImageSet.XPFileExplorer: {
                                _cachedExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_XP_Explorer_Expand.gif");
                                break;
                            }
                        case TreeViewImageSet.Msdn: {
                                _cachedExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_MSDN_Expand.gif");
                                break;
                            }
                        case TreeViewImageSet.WindowsHelp: {
                                _cachedExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Windows_Help_Expand.gif");
                                break;
                            }
                        case TreeViewImageSet.Custom: {
                                _cachedExpandImageUrl = ExpandImageUrl;
                                break;
                            }
                        default: {
                                _cachedExpandImageUrl = String.Empty;
                                break;
                            }
                    }
                }
                return _cachedExpandImageUrl;
            }
        }


        /// <devdoc>
        ///     Gets the hidden field ID for the expand state of this TreeView
        /// </devdoc>
        internal string ExpandStateID {
            get {
                if (_cachedExpandStateID == null) {
                    _cachedExpandStateID = ClientID + "_ExpandState";
                }
                return _cachedExpandStateID;
            }
        }


        /// <devdoc>
        ///     Gets the hover style properties for nodes.
        /// </devdoc>
        [
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebCategory("Styles"),
        WebSysDescription(SR.TreeView_HoverNodeStyle)
        ]
        public Style HoverNodeStyle {
            get {
                if (_hoverNodeStyle == null) {
                    _hoverNodeStyle = new Style();
                    if (IsTrackingViewState) {
                        ((IStateManager)_hoverNodeStyle).TrackViewState();
                    }
                }
                return _hoverNodeStyle;
            }
        }

        /// <devdoc>
        /// ID of the client-side array of images (expand, collapse, lines, etc.)
        /// </devdoc>
        internal string ImageArrayID {
            get {
                if (_cachedImageArrayID == null) {
                    _cachedImageArrayID = ClientID + "_ImageArray";
                }
                return _cachedImageArrayID;
            }
        }


        [DefaultValue(TreeViewImageSet.Custom)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_ImageSet)]
        public TreeViewImageSet ImageSet {
            get {
                object o = ViewState["ImageSet"];
                if (o == null) {
                    return TreeViewImageSet.Custom;
                }
                return (TreeViewImageSet)o;
            }
            set {
                if (value < TreeViewImageSet.Custom || value > TreeViewImageSet.Faq) {
                    throw new ArgumentOutOfRangeException("value");
                }
                ViewState["ImageSet"] = value;
            }
        }


        /// <devdoc>
        ///     An cache of urls for the line and node type images.
        /// </devdoc>
        private string[] ImageUrls {
            get {
                if (_imageUrls == null) {
                    _imageUrls = new string[ImageUrlsCount];
                }
                return _imageUrls;
            }
        }


        /// <devdoc>
        ///     Gets whether the current browser is IE
        /// </devdoc>
        internal bool IsNotIE {
            get {
                return _isNotIE;
            }
        }


        /// <devdoc>
        ///     Gets the style properties of leaf nodes in the tree.
        /// </devdoc>
        [
        WebCategory("Styles"),
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.TreeView_LeafNodeStyle)
        ]
        public TreeNodeStyle LeafNodeStyle {
            get {
                if (_leafNodeStyle == null) {
                    _leafNodeStyle = new TreeNodeStyle();
                    if (IsTrackingViewState) {
                        ((IStateManager)_leafNodeStyle).TrackViewState();
                    }
                }
                return _leafNodeStyle;
            }
        }

        private string[] LevelImageUrls {
            get {
                if (_levelImageUrls == null) {
                    _levelImageUrls = new string[LevelStyles.Count];
                }
                return _levelImageUrls;
            }
        }



        /// <devdoc>
        ///     Gets the collection of TreeNodeStyles corresponding to the each level
        /// </devdoc>
        [
        DefaultValue(null),
        Editor("System.Web.UI.Design.WebControls.TreeNodeStyleCollectionEditor," + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebCategory("Styles"),
        WebSysDescription(SR.TreeView_LevelStyles),
        ]
        public TreeNodeStyleCollection LevelStyles {
            get {
                if (_levelStyles == null) {
                    _levelStyles = new TreeNodeStyleCollection();
                    if (IsTrackingViewState) {
                        ((IStateManager)_levelStyles).TrackViewState();
                    }
                }

                return _levelStyles;
            }
        }


        /// <devdoc>
        ///     Gets and sets the url pointing to a folder containing TreeView line images.
        /// </devdoc>
        [DefaultValue("")]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_LineImagesFolderUrl)]
        public string LineImagesFolder {
            get {
                string s = (string)ViewState["LineImagesFolder"];
                if (s == null) {
                    return String.Empty;
                }
                return s;
            }
            set {
                ViewState["LineImagesFolder"] = value;
            }
        }


        /// <devdoc>
        ///     True is we are loading the state of a node that has changed on the client, specifically,
        ///     this is used by TreeNode.Expand to check if it needs to trigger a populate or not
        /// </devdoc>
        internal bool LoadingNodeState {
            get {
                return _loadingNodeState;
            }
        }


        /// <devdoc>
        ///     The maximum depth to which the TreeView will bind.
        /// </devdoc>
        [WebCategory("Behavior")]
        [DefaultValue(-1)]
        [WebSysDescription(SR.TreeView_MaxDataBindDepth)]
        public int MaxDataBindDepth {
            get {
                object o = ViewState["MaxDataBindDepth"];
                if (o == null) {
                    return -1;
                }
                return (int)o;
            }
            set {
                if (value < -1) {
                    throw new ArgumentOutOfRangeException("value");
                }
                ViewState["MaxDataBindDepth"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets the image url for the non-expandable node indicator icon.
        /// </devdoc>
        [DefaultValue("")]
        [Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
        [UrlProperty()]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_NoExpandImageUrl)]
        public string NoExpandImageUrl {
            get {
                string s = (string)ViewState["NoExpandImageUrl"];
                if (s == null) {
                    return String.Empty;
                }
                return s;
            }
            set {
                ViewState["NoExpandImageUrl"] = value;
            }
        }

        internal string NoExpandImageUrlInternal {
            get {
                if (_cachedNoExpandImageUrl == null) {
                    switch (ImageSet) {
                        case TreeViewImageSet.Simple: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Simple_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.Simple2: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Simple2_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.Arrows: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Arrows_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.Contacts: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Contacts_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.XPFileExplorer: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_XP_Explorer_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.Msdn: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_MSDN_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.WindowsHelp: {
                                _cachedNoExpandImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Windows_Help_NoExpand.gif");
                                break;
                            }
                        case TreeViewImageSet.Custom: {
                                _cachedNoExpandImageUrl = NoExpandImageUrl;
                                break;
                            }
                        default: {
                                _cachedNoExpandImageUrl = String.Empty;
                                break;
                            }
                    }
                }
                return _cachedNoExpandImageUrl;
            }
        }


        /// <devdoc>
        ///     Gets and sets the indent width of each node
        /// </devdoc>
        [DefaultValue(20)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_NodeIndent)]
        public int NodeIndent {
            get {
                object o = ViewState["NodeIndent"];
                if (o == null) {
                    return 20;
                }
                return (int)o;
            }
            set {
                ViewState["NodeIndent"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets whether the text of the nodes should be wrapped
        /// </devdoc>
        [DefaultValue(false)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_NodeWrap)]
        public bool NodeWrap {
            get {
                object o = ViewState["NodeWrap"];
                if (o == null) {
                    return false;
                }
                return (bool)o;
            }
            set {
                ViewState["NodeWrap"] = value;
            }
        }


        /// <devdoc>
        ///     Gets the collection of top-level nodes.
        /// </devdoc>
        [
        DefaultValue(null),
        MergableProperty(false),
        Editor("System.Web.UI.Design.WebControls.TreeNodeCollectionEditor," + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.TreeView_Nodes)
        ]
        public TreeNodeCollection Nodes {
            get {
                return RootNode.ChildNodes;
            }
        }



        /// <devdoc>
        ///     Gets the style properties of nodes in the tree.
        /// </devdoc>
        [
        WebCategory("Styles"),
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.TreeView_NodeStyle)
        ]
        public TreeNodeStyle NodeStyle {
            get {
                if (_nodeStyle == null) {
                    _nodeStyle = new TreeNodeStyle();
                    if (IsTrackingViewState) {
                        ((IStateManager)_nodeStyle).TrackViewState();
                    }
                }
                return _nodeStyle;
            }
        }


        /// <devdoc>
        ///     Gets the style properties of parent nodes in the tree.
        /// </devdoc>
        [
        WebCategory("Styles"),
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.TreeView_ParentNodeStyle)
        ]
        public TreeNodeStyle ParentNodeStyle {
            get {
                if (_parentNodeStyle == null) {
                    _parentNodeStyle = new TreeNodeStyle();
                    if (IsTrackingViewState) {
                        ((IStateManager)_parentNodeStyle).TrackViewState();
                    }
                }
                return _parentNodeStyle;
            }
        }


        /// <devdoc>
        ///     Gets and sets the character used to delimit paths.
        /// </devdoc>
        [DefaultValue('/')]
        [WebSysDescription(SR.TreeView_PathSeparator)]
        public char PathSeparator {
            get {
                object o = ViewState["PathSeparator"];
                if (o == null) {
                    return '/';
                }
                return (char)o;
            }
            set {
                if (value == '\0') {
                    ViewState["PathSeparator"] = null;
                }
                else {
                    ViewState["PathSeparator"] = value;
                }
                foreach (TreeNode node in Nodes) {
                    node.ResetValuePathRecursive();
                }
            }
        }


        /// <devdoc>
        ///     Gets the hidden field ID for the expand state of this TreeView
        /// </devdoc>
        internal string PopulateLogID {
            get {
                if (_cachedPopulateLogID == null) {
                    _cachedPopulateLogID = ClientID + "_PopulateLog";
                }
                return _cachedPopulateLogID;
            }
        }


        /// <devdoc>
        ///     Gets and sets whether the tree view should populate nodes from the client (if supported)
        /// </devdoc>
        [DefaultValue(true)]
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_PopulateNodesFromClient)]
        public bool PopulateNodesFromClient {
            get {
                if (!DesignMode &&
                    (Page != null && !Page.Request.Browser.SupportsCallback)) {
                    return false;
                }
                object o = ViewState["PopulateNodesFromClient"];
                if (o == null) {
                    return true;
                }
                return (bool)o;
            }
            set {
                ViewState["PopulateNodesFromClient"] = value;
            }
        }

        /// <devdoc>
        ///     Gets whether we should be rendering client script or not
        /// </devdoc>
        internal bool RenderClientScript {
            get {
                return _renderClientScript;
            }
        }


        /// <devdoc>
        ///     The 'virtual' root node of the tree
        /// </devdoc>
        internal TreeNode RootNode {
            get {
                if (_rootNode == null) {
                    // Using the constructor only here. Other places should use CreateNode.
                    _rootNode = new TreeNode(this, true);
                }
                return _rootNode;
            }
        }

        // BaseTreeNodeStyle is roughly equivalent to ControlStyle.HyperLinkStyle if it existed.
        internal Style BaseTreeNodeStyle {
            get {
                if (_baseNodeStyle == null) {
                    _baseNodeStyle = new Style();
                    _baseNodeStyle.Font.CopyFrom(Font);
                    if (!ForeColor.IsEmpty) {
                        _baseNodeStyle.ForeColor = ForeColor;
                    }
                    // Not defaulting to black anymore for not entirely satisfying but reasonable reasons (VSWhidbey 356729)
                    if (!ControlStyle.IsSet(System.Web.UI.WebControls.Style.PROP_FONT_UNDERLINE)) {
                        _baseNodeStyle.Font.Underline = false;
                    }
                }
                return _baseNodeStyle;
            }
        }


        /// <devdoc>
        ///     Gets the style properties of root nodes in the tree.
        /// </devdoc>
        [
        WebCategory("Styles"),
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.TreeView_RootNodeStyle)
        ]
        public TreeNodeStyle RootNodeStyle {
            get {
                if (_rootNodeStyle == null) {
                    _rootNodeStyle = new TreeNodeStyle();
                    if (IsTrackingViewState) {
                        ((IStateManager)_rootNodeStyle).TrackViewState();
                    }
                }
                return _rootNodeStyle;
            }
        }


        /// <devdoc>
        ///     Gets and sets the TreeView's selected node.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ]
        public TreeNode SelectedNode {
            get {
                return _selectedNode;
            }
        }


        /// <devdoc>
        ///     Gets the tag ID for hidden field containing the id of the selected node of this TreeView
        /// </devdoc>
        internal string SelectedNodeFieldID {
            get {
                if (_cachedSelectedNodeFieldID == null) {
                    _cachedSelectedNodeFieldID = ClientID + "_SelectedNode";
                }
                return _cachedSelectedNodeFieldID;
            }
        }


        /// <devdoc>
        ///     Gets the style properties of the selected node in the tree.
        /// </devdoc>
        [
        WebCategory("Styles"),
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.TreeView_SelectedNodeStyle)
        ]
        public TreeNodeStyle SelectedNodeStyle {
            get {
                if (_selectedNodeStyle == null) {
                    _selectedNodeStyle = new TreeNodeStyle();
                    if (IsTrackingViewState) {
                        ((IStateManager)_selectedNodeStyle).TrackViewState();
                    }
                }
                return _selectedNodeStyle;
            }
        }


        [Browsable(false)]
        [DefaultValue("")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string SelectedValue {
            get {
                if (SelectedNode != null) {
                    return SelectedNode.Value;
                }

                return String.Empty;
            }
        }


        /// <devdoc>
        ///     Gets and sets whether to show check boxes next to specific types of nodes in the tree
        /// </devdoc>
        [DefaultValue(TreeNodeTypes.None)]
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_ShowCheckBoxes)]
        public TreeNodeTypes ShowCheckBoxes {
            get {
                object o = ViewState["ShowCheckBoxes"];
                if (o == null) {
                    return TreeNodeTypes.None;
                }
                return (TreeNodeTypes)o;
            }
            set {
                if ((value < TreeNodeTypes.None) || (value > TreeNodeTypes.All)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                ViewState["ShowCheckBoxes"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets whether to show the expander icon next to nodes in the tree
        /// </devdoc>
        [DefaultValue(true)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_ShowExpandCollapse)]
        public bool ShowExpandCollapse {
            get {
                object o = ViewState["ShowExpandCollapse"];
                if (o == null) {
                    return true;
                }
                return (bool)o;
            }
            set {
                ViewState["ShowExpandCollapse"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets whether the TreeView should show lines.
        /// </devdoc>
        [DefaultValue(false)]
        [WebCategory("Appearance")]
        [WebSysDescription(SR.TreeView_ShowLines)]
        public bool ShowLines {
            get {
                object o = ViewState["ShowLines"];
                if (o == null) {
                    return false;
                }
                return (bool)o;
            }
            set {
                ViewState["ShowLines"] = value;
            }
        }

        [
        Localizable(true),
        WebCategory("Accessibility"),
        WebSysDefaultValue(SR.TreeView_Default_SkipLinkText),
        WebSysDescription(SR.TreeView_SkipLinkText)
        ]
        public String SkipLinkText {
            get {
                string s = ViewState["SkipLinkText"] as String;
                return s == null ? SR.GetString(SR.TreeView_Default_SkipLinkText) : s;
            }
            set {
                ViewState["SkipLinkText"] = value;
            }
        }


        /// <devdoc>
        ///     Gets and sets the target window that the TreeNodes will browse to if selected
        /// </devdoc>
        [DefaultValue("")]
        [WebSysDescription(SR.TreeNode_Target)]
        public string Target {
            get {
                string s = (string)ViewState["Target"];
                if (s == null) {
                    return String.Empty;
                }
                return s;
            }
            set {
                ViewState["Target"] = value;
            }
        }


        protected override HtmlTextWriterTag TagKey {
            get {
                return DesignMode ? HtmlTextWriterTag.Table : HtmlTextWriterTag.Div;
            }
        }

        public override bool Visible {
            get {
                return base.Visible;
            }
            set {
                // Remember that the tree was initially invisible and thus never expanded (VSWhidbey 349279)
                // See SaveViewState to see the code that sets this flag.
                if ((value == true) && (Page != null) && Page.IsPostBack &&
                    (ViewState["NeverExpanded"] != null) &&
                    ((bool)ViewState["NeverExpanded"] == true)) {

                    // This will reset the viewstate flag and expand the tree
                    ExpandToDepth(Nodes, ExpandDepth);
                }
                base.Visible = value;
            }
        }

        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_CheckChanged)]
        public event TreeNodeEventHandler TreeNodeCheckChanged {
            add {
                Events.AddHandler(CheckChangedEvent, value);
            }
            remove {
                Events.RemoveHandler(CheckChangedEvent, value);
            }
        }


        /// <devdoc>
        ///     Triggered when the TreeView's selected node has changed.
        /// </devdoc>
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_SelectedNodeChanged)]
        public event EventHandler SelectedNodeChanged {
            add {
                Events.AddHandler(SelectedNodeChangedEvent, value);
            }
            remove {
                Events.RemoveHandler(SelectedNodeChangedEvent, value);
            }
        }


        /// <devdoc>
        ///     Triggered when a TreeNode has collapsed its children.
        /// </devdoc>
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_TreeNodeCollapsed)]
        public event TreeNodeEventHandler TreeNodeCollapsed {
            add {
                Events.AddHandler(TreeNodeCollapsedEvent, value);
            }
            remove {
                Events.RemoveHandler(TreeNodeCollapsedEvent, value);
            }
        }


        /// <devdoc>
        ///     Triggered when a TreeNode has been databound.
        /// </devdoc>
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_TreeNodeDataBound)]
        public event TreeNodeEventHandler TreeNodeDataBound {
            add {
                Events.AddHandler(TreeNodeDataBoundEvent, value);
            }
            remove {
                Events.RemoveHandler(TreeNodeDataBoundEvent, value);
            }
        }


        /// <devdoc>
        ///     Triggered when a TreeNode has expanded its children.
        /// </devdoc>
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_TreeNodeExpanded)]
        public event TreeNodeEventHandler TreeNodeExpanded {
            add {
                Events.AddHandler(TreeNodeExpandedEvent, value);
            }
            remove {
                Events.RemoveHandler(TreeNodeExpandedEvent, value);
            }
        }


        /// <devdoc>
        ///     Triggered when a TreeNode is populating its children.
        /// </devdoc>
        [WebCategory("Behavior")]
        [WebSysDescription(SR.TreeView_TreeNodePopulate)]
        public event TreeNodeEventHandler TreeNodePopulate {
            add {
                Events.AddHandler(TreeNodePopulateEvent, value);
            }
            remove {
                Events.RemoveHandler(TreeNodePopulateEvent, value);
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer) {

            // Make sure we are in a form tag with runat=server.
            if (Page != null) {
                Page.VerifyRenderingInServerForm(this);
            }

            string oldAccessKey = AccessKey;
            if (!String.IsNullOrEmpty(oldAccessKey)) {
                AccessKey = String.Empty;
                base.AddAttributesToRender(writer);
                AccessKey = oldAccessKey;
            }
            else {
                base.AddAttributesToRender(writer);
            }
        }

        // returns true if the style contains a class name
        private static bool AppendCssClassName(StringBuilder builder, TreeNodeStyle style, bool hyperlink) {
            bool containsClassName = false;
            if (style != null) {
                // We have to merge with any CssClass specified on the Style itself
                if (style.CssClass.Length != 0) {
                    builder.Append(style.CssClass);
                    builder.Append(' ');
                    containsClassName = true;
                }

                string className = (hyperlink ?
                    style.HyperLinkStyle.RegisteredCssClass :
                    style.RegisteredCssClass);
                if (className.Length > 0) {
                    builder.Append(className);
                    builder.Append(' ');
                }
            }
            return containsClassName;
        }

        private static T CacheGetItem<T>(List<T> cacheList, int index) where T : class {
            Debug.Assert(cacheList != null);
            if (index < cacheList.Count) return cacheList[index];
            return null;
        }

        private static void CacheSetItem<T>(List<T> cacheList, int index, T item) where T : class {
            if (cacheList.Count > index) {
                cacheList[index] = item;
            }
            else {
                for (int i = cacheList.Count; i < index; i++) {
                    cacheList.Add(null);
                }
                cacheList.Add(item);
            }
        }


        /// <devdoc>
        ///     Fully collapses all nodes in the tree
        /// </devdoc>
        public void CollapseAll() {
            foreach (TreeNode node in Nodes) {
                node.CollapseAll();
            }
        }


        /// <devdoc>
        ///     Overridden to disallow adding controls
        /// </devdoc>
        protected override ControlCollection CreateControlCollection() {
            return new EmptyControlCollection(this);
        }

        protected virtual internal TreeNode CreateNode() {
            return new TreeNode(this, false);
        }


        /// <devdoc>
        ///     Creates a tree node ID based on an index
        /// </devdoc>
        internal string CreateNodeId(int index) {
            return ClientID + "n" + index;
        }


        /// <devdoc>
        ///     Creates a tree node text ID based on an index
        /// </devdoc>
        internal string CreateNodeTextId(int index) {
            return ClientID + "t" + index;
        }

        /// Data bound controls should override PerformDataBinding instead
        /// of DataBind.  If DataBind if overridden, the OnDataBinding and OnDataBound events will
        /// fire in the wrong order.  However, for backwards compat on ListControl and AdRotator, we 
        /// can't seal this method.  It is sealed on all new BaseDataBoundControl-derived controls.
        public override sealed void DataBind() {
            base.DataBind();
        }


        /// <devdoc>
        ///     Databinds the specified node to the datasource
        /// </devdoc>
        private void DataBindNode(TreeNode node) {
            if (node.PopulateOnDemand && !IsBoundUsingDataSourceID && !DesignMode) {
                throw new InvalidOperationException(SR.GetString(SR.TreeView_PopulateOnlyForDataSourceControls, ID));
            }

            HierarchicalDataSourceView view = GetData(node.DataPath);
            // Do nothing if no datasource was set
            if (!IsBoundUsingDataSourceID && (DataSource == null)) {
                return;
            }

            if (view == null) {
                throw new InvalidOperationException(SR.GetString(SR.TreeView_DataSourceReturnedNullView, ID));
            }
            IHierarchicalEnumerable enumerable = view.Select();
            node.ChildNodes.Clear();
            if (enumerable != null) {
                // If we're bound to a SiteMapDataSource, automatically select the node
                if (IsBoundUsingDataSourceID) {
                    SiteMapDataSource siteMapDataSource = GetDataSource() as SiteMapDataSource;
                    if (siteMapDataSource != null) {
                        if (_currentSiteMapNodeDataPath == null) {
                            IHierarchyData currentNodeData = (IHierarchyData)siteMapDataSource.Provider.CurrentNode;
                            if (currentNodeData != null) {
                                _currentSiteMapNodeDataPath = currentNodeData.Path;
                            }
                            else {
                                _currentSiteMapNodeDataPath = String.Empty;
                            }
                        }
                    }
                }

                DataBindRecursive(node, enumerable, true);
            }
        }


        /// <devdoc>
        ///     Databinds recursively, using the TreeView's Bindings collection, until it reaches a TreeNodeBinding
        ///     that is PopulateOnDemand or there is no more data.  Optionally ignores the first level's PopulateOnDemand
        ///     to facilitate populating that level
        /// </devdoc>
        private void DataBindRecursive(TreeNode node, IHierarchicalEnumerable enumerable, bool ignorePopulateOnDemand) {
            // Since we are binding children, get the level below the current node's depth
            int depth = checked(node.Depth + 1);

            // Don't databind beyond the maximum specified depth
            if ((MaxDataBindDepth != -1) && (depth > MaxDataBindDepth)) {
                return;
            }

            foreach (object item in enumerable) {
                IHierarchyData data = enumerable.GetHierarchyData(item);

                string text = null;
                string value = null;
                string navigateUrl = String.Empty;
                string imageUrl = String.Empty;
                string target = String.Empty;

                string toolTip = String.Empty;
                string imageToolTip = String.Empty;
                TreeNodeSelectAction selectAction = TreeNodeSelectAction.Select;
                bool? showCheckBox = null;

                string dataMember = String.Empty;
                bool populateOnDemand = false;

                dataMember = data.Type;

                TreeNodeBinding level = DataBindings.GetBinding(dataMember, depth);

                if (level != null) {
                    populateOnDemand = level.PopulateOnDemand;

                    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(item);

                    // Bind Text, using the static value if necessary
                    string textField = level.TextField;
                    if (textField.Length > 0) {
                        PropertyDescriptor desc = props.Find(textField, true);
                        if (desc != null) {
                            object objData = desc.GetValue(item);
                            if (objData != null) {
                                if (!String.IsNullOrEmpty(level.FormatString)) {
                                    text = string.Format(CultureInfo.CurrentCulture, level.FormatString, objData);
                                }
                                else {
                                    text = objData.ToString();
                                }
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, textField, "TextField"));
                        }
                    }

                    if (String.IsNullOrEmpty(text)) {
                        text = level.Text;
                    }

                    // Bind Value, using the static value if necessary
                    string valueField = level.ValueField;
                    if (valueField.Length > 0) {
                        PropertyDescriptor desc = props.Find(valueField, true);
                        if (desc != null) {
                            object objData = desc.GetValue(item);
                            if (objData != null) {
                                value = objData.ToString();
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, valueField, "ValueField"));
                        }
                    }

                    if (String.IsNullOrEmpty(value)) {
                        value = level.Value;
                    }

                    // Bind ImageUrl, using the static value if necessary
                    string imageUrlField = level.ImageUrlField;
                    if (imageUrlField.Length > 0) {
                        PropertyDescriptor desc = props.Find(imageUrlField, true);
                        if (desc != null) {
                            object objData = desc.GetValue(item);
                            if (objData != null) {
                                imageUrl = objData.ToString();
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, imageUrlField, "ImageUrlField"));
                        }
                    }

                    if (imageUrl.Length == 0) {
                        imageUrl = level.ImageUrl;
                    }

                    // Bind NavigateUrl, using the static value if necessary
                    string navigateUrlField = level.NavigateUrlField;
                    if (navigateUrlField.Length > 0) {
                        PropertyDescriptor desc = props.Find(navigateUrlField, true);
                        if (desc != null) {
                            object objData = desc.GetValue(item);
                            if (objData != null) {
                                navigateUrl = objData.ToString();
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, navigateUrlField, "NavigateUrlField"));
                        }
                    }

                    if (navigateUrl.Length == 0) {
                        navigateUrl = level.NavigateUrl;
                    }

                    // Bind Target, using the static value if necessary
                    string targetField = level.TargetField;
                    if (targetField.Length > 0) {
                        PropertyDescriptor desc = props.Find(targetField, true);
                        if (desc != null) {
                            object objData = desc.GetValue(item);
                            if (objData != null) {
                                target = objData.ToString();
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, targetField, "TargetField"));
                        }
                    }

                    if (String.IsNullOrEmpty(target)) {
                        target = level.Target;
                    }

                    // Bind ToolTip, using the static value if necessary
                    string toolTipField = level.ToolTipField;
                    if (toolTipField.Length > 0) {
                        PropertyDescriptor desc = props.Find(toolTipField, true);
                        if (desc != null) {
                            object objData = desc.GetValue(item);
                            if (objData != null) {
                                toolTip = objData.ToString();
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, toolTipField, "ToolTipField"));
                        }
                    }

                    if (toolTip.Length == 0) {
                        toolTip = level.ToolTip;
                    }

                    // Bind ImageToolTip, using the static value if necessary
                    string imageToolTipField = level.ImageToolTipField;

                    if (imageToolTipField.Length > 0) {
                        PropertyDescriptor desc = props.Find(imageToolTipField, true);

                        if (desc != null) {
                            object objData = desc.GetValue(item);

                            if (objData != null) {
                                imageToolTip = objData.ToString();
                            }
                        }
                        else {
                            throw new InvalidOperationException(SR.GetString(SR.TreeView_InvalidDataBinding, imageToolTipField, "imageToolTipField"));
                        }
                    }

                    if (imageToolTip.Length == 0) {
                        imageToolTip = level.ImageToolTip;
                    }

                    // Set the other static properties
                    selectAction = level.SelectAction;
                    showCheckBox = level.ShowCheckBox;
                }
                else {
                    if (item is INavigateUIData) {
                        INavigateUIData navigateUIData = (INavigateUIData)item;
                        text = navigateUIData.Name;
                        value = navigateUIData.Value;
                        navigateUrl = navigateUIData.NavigateUrl;
                        if (String.IsNullOrEmpty(navigateUrl)) {
                            selectAction = TreeNodeSelectAction.None;
                        }
                        toolTip = navigateUIData.Description;
                    }
                    if (IsBoundUsingDataSourceID) {
                        populateOnDemand = PopulateNodesFromClient;
                    }
                }

                if (AutoGenerateDataBindings && (text == null)) {
                    text = item.ToString();
                }

                TreeNode newNode = null;
                // Allow String.Empty for the text, but not null
                if ((text != null) || (value != null)) {
                    newNode = CreateNode();
                    if (!String.IsNullOrEmpty(text)) {
                        newNode.Text = text;
                    }
                    if (!String.IsNullOrEmpty(value)) {
                        newNode.Value = value;
                    }
                    if (!String.IsNullOrEmpty(imageUrl)) {
                        newNode.ImageUrl = imageUrl;
                    }
                    if (!String.IsNullOrEmpty(navigateUrl)) {
                        newNode.NavigateUrl = navigateUrl;
                    }
                    if (!String.IsNullOrEmpty(target)) {
                        newNode.Target = target;
                    }
                }

                if (newNode != null) {
                    if (!String.IsNullOrEmpty(toolTip)) {
                        newNode.ToolTip = toolTip;
                    }

                    if (!String.IsNullOrEmpty(imageToolTip)) {
                        newNode.ImageToolTip = imageToolTip;
                    }

                    if (selectAction != newNode.SelectAction) {
                        newNode.SelectAction = selectAction;
                    }

                    if (showCheckBox != null) {
                        newNode.ShowCheckBox = showCheckBox;
                    }

                    newNode.SetDataPath(data.Path);
                    newNode.SetDataBound(true);

                    node.ChildNodes.Add(newNode);

                    if (String.Equals(data.Path, _currentSiteMapNodeDataPath, StringComparison.OrdinalIgnoreCase)) {
                        newNode.Selected = true;

                        // Make sure the newly selected node's parents are expanded
                        if ((Page == null) || !Page.IsCallback) {
                            TreeNode newNodeParent = newNode.Parent;
                            while (newNodeParent != null) {
                                if (newNodeParent.Expanded != true) {
                                    newNodeParent.Expanded = true;
                                }

                                newNodeParent = newNodeParent.Parent;
                            }
                        }
                    }

                    // Make sure we call user code if they've hooked the populate event
                    newNode.SetDataItem(data.Item);
                    OnTreeNodeDataBound(new TreeNodeEventArgs(newNode));
                    newNode.SetDataItem(null);

                    if ((data.HasChildren) && ((MaxDataBindDepth == -1) || (depth < MaxDataBindDepth))) {
                        if (populateOnDemand && !DesignMode) {
                            newNode.PopulateOnDemand = true;
                        }
                        else {
                            IHierarchicalEnumerable newEnumerable = data.GetChildren();
                            if (newEnumerable != null) {
                                DataBindRecursive(newNode, newEnumerable, false);
                            }
                        }
                    }
                }
            }
        }

        /// <devdoc>
        ///     Make sure we are set up to render
        /// </devdoc>
        private void EnsureRenderSettings() {
            HttpBrowserCapabilities caps = Page.Request.Browser;
            _isNotIE = (Page.Request.Browser.MSDomVersion.Major < 4);
            _renderClientScript = GetRenderClientScript(caps);

            if (_hoverNodeStyle != null && Page != null && Page.Header == null) {
                throw new InvalidOperationException(SR.GetString(SR.NeedHeader, "TreeView.HoverStyle"));
            }

            if (Page != null && (Page.SupportsStyleSheets ||
                Page.IsCallback || (Page.ScriptManager != null && Page.ScriptManager.IsInAsyncPostBack))) {
                // Register the styles. NB the order here is important: later wins over earlier
                RegisterStyle(BaseTreeNodeStyle);

                // It's also vitally important to register hyperlinkstyles BEFORE
                // their associated styles as we need to copy the data from this style
                // and a registered style appears empty except for RegisteredClassName
                if (_nodeStyle != null) {
                    _nodeStyle.HyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(_nodeStyle.HyperLinkStyle);
                    RegisterStyle(_nodeStyle);
                }

                if (_rootNodeStyle != null) {
                    _rootNodeStyle.HyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(_rootNodeStyle.HyperLinkStyle);
                    RegisterStyle(_rootNodeStyle);
                }

                if (_parentNodeStyle != null) {
                    _parentNodeStyle.HyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(_parentNodeStyle.HyperLinkStyle);
                    RegisterStyle(_parentNodeStyle);
                }

                if (_leafNodeStyle != null) {
                    _leafNodeStyle.HyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(_leafNodeStyle.HyperLinkStyle);
                    RegisterStyle(_leafNodeStyle);
                }

                foreach (TreeNodeStyle style in LevelStyles) {
                    style.HyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(style.HyperLinkStyle);
                    RegisterStyle(style);
                }

                if (_selectedNodeStyle != null) {
                    _selectedNodeStyle.HyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(_selectedNodeStyle.HyperLinkStyle);
                    RegisterStyle(_selectedNodeStyle);
                }

                if (_hoverNodeStyle != null) {
                    _hoverNodeHyperLinkStyle = new HyperLinkStyle(_hoverNodeStyle);
                    _hoverNodeHyperLinkStyle.DoNotRenderDefaults = true;
                    RegisterStyle(_hoverNodeHyperLinkStyle);
                    RegisterStyle(_hoverNodeStyle);
                }
            }
        }


        /// <devdoc>
        ///     Fully expands all nodes in the tree
        /// </devdoc>
        public void ExpandAll() {
            foreach (TreeNode node in Nodes) {
                node.ExpandAll();
            }
        }

        private void ExpandToDepth(TreeNodeCollection nodes, int depth) {
            // Reset the memory that the tree was never expanded (VSWhidbey 349279)
            ViewState["NeverExpanded"] = null;

            foreach (TreeNode node in nodes) {
                if ((depth == -1) || (node.Depth < depth)) {
                    // Only expanding nodes that have not been set, not those that have explicit Expanded=False.
                    if (node.Expanded == null) {
                        node.Expanded = true;
                        // No need to populate as setting Expanded to true already does the job.
                    }
                    ExpandToDepth(node.ChildNodes, depth);
                }
            }
        }


        public TreeNode FindNode(string valuePath) {
            if (valuePath == null) {
                return null;
            }
            return Nodes.FindNode(valuePath.Split(PathSeparator), 0);
        }

        internal string GetCssClassName(TreeNode node, bool hyperLink) {
            bool discarded;
            return GetCssClassName(node, hyperLink, out discarded);
        }

        internal string GetCssClassName(TreeNode node, bool hyperLink, out bool containsClassName) {
            if (node == null) {
                throw new ArgumentNullException("node");
            }

            containsClassName = false;
            int depth = node.Depth;
            bool parent = node.ChildNodes.Count != 0 || node.PopulateOnDemand;
            List<string> cache = parent ?
                (hyperLink ? CachedParentNodeHyperLinkClassNames : CachedParentNodeClassNames) :
                (hyperLink ? CachedLeafNodeHyperLinkClassNames : CachedLeafNodeClassNames);
            string baseClassName = CacheGetItem<string>(cache, depth);
            if (CachedLevelsContainingCssClass.Contains(depth)) {
                containsClassName = true;
            }

            bool needsSelectedStyle = node.Selected && _selectedNodeStyle != null;

            if (!needsSelectedStyle && (baseClassName != null)) {
                return baseClassName;
            }

            StringBuilder builder = new StringBuilder();
            if (baseClassName != null) {
                builder.Append(baseClassName);
                builder.Append(' ');
            }
            else {
                // No cached style, so build it
                if (hyperLink) {
                    builder.Append(BaseTreeNodeStyle.RegisteredCssClass);
                    builder.Append(' ');
                }

                containsClassName |= AppendCssClassName(builder, _nodeStyle, hyperLink);

                if (depth < LevelStyles.Count && LevelStyles[depth] != null) {
                    containsClassName |= AppendCssClassName(builder, (TreeNodeStyle)LevelStyles[depth], hyperLink);
                }
                if (depth == 0 && parent) {
                    containsClassName |= AppendCssClassName(builder, _rootNodeStyle, hyperLink);
                }
                else if (parent) {
                    containsClassName |= AppendCssClassName(builder, _parentNodeStyle, hyperLink);
                }
                else {
                    containsClassName |= AppendCssClassName(builder, _leafNodeStyle, hyperLink);
                }

                baseClassName = builder.ToString().Trim();
                CacheSetItem<string>(cache, depth, baseClassName);
                if (containsClassName && !CachedLevelsContainingCssClass.Contains(depth)) {
                    CachedLevelsContainingCssClass.Add(depth);
                }
            }

            if (needsSelectedStyle) {
                containsClassName |= AppendCssClassName(builder, _selectedNodeStyle, hyperLink);
                return builder.ToString().Trim(); ;
            }
            return baseClassName;
        }


        /// <devdoc>
        ///     Gets the URL for the specified image, properly pathing the image filename depending on which image it is
        /// </devdoc>
        internal string GetImageUrl(int index) {
            if (ImageUrls[index] == null) {
                switch (index) {
                    case RootImageIndex:
                        string rootNodeImageUrl = RootNodeStyle.ImageUrl;
                        if (rootNodeImageUrl.Length == 0) {
                            rootNodeImageUrl = NodeStyle.ImageUrl;
                        }
                        if (rootNodeImageUrl.Length == 0) {
                            switch (ImageSet) {
                                case TreeViewImageSet.BulletedList: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList2: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList2_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList3: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList3_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList4: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList4_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.News: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_News_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Inbox: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Inbox_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Events: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Events_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Faq: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_FAQ_RootNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.XPFileExplorer: {
                                        rootNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_XP_Explorer_RootNode.gif");
                                        break;
                                    }
                            }
                        }

                        if (rootNodeImageUrl.Length != 0) {
                            rootNodeImageUrl = ResolveClientUrl(rootNodeImageUrl);
                        }
                        ImageUrls[index] = rootNodeImageUrl;
                        break;
                    case ParentImageIndex:
                        string parentNodeImageUrl = ParentNodeStyle.ImageUrl;
                        if (parentNodeImageUrl.Length == 0) {
                            parentNodeImageUrl = NodeStyle.ImageUrl;
                        }
                        if (parentNodeImageUrl.Length == 0) {
                            switch (ImageSet) {
                                case TreeViewImageSet.BulletedList: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList2: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList2_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList3: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList3_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList4: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList4_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.News: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_News_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Inbox: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Inbox_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Events: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Events_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Faq: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_FAQ_ParentNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.XPFileExplorer: {
                                        parentNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_XP_Explorer_ParentNode.gif");
                                        break;
                                    }
                            }
                        }


                        if (parentNodeImageUrl.Length != 0) {
                            parentNodeImageUrl = ResolveClientUrl(parentNodeImageUrl);
                        }
                        ImageUrls[index] = parentNodeImageUrl;
                        break;
                    case LeafImageIndex:
                        string leafNodeImageUrl = LeafNodeStyle.ImageUrl;
                        if (leafNodeImageUrl.Length == 0) {
                            leafNodeImageUrl = NodeStyle.ImageUrl;
                        }
                        if (leafNodeImageUrl.Length == 0) {
                            switch (ImageSet) {
                                case TreeViewImageSet.BulletedList: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList2: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList2_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList3: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList3_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.BulletedList4: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_BulletedList4_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.News: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_News_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Inbox: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Inbox_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Events: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Events_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.Faq: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_FAQ_LeafNode.gif");
                                        break;
                                    }
                                case TreeViewImageSet.XPFileExplorer: {
                                        leafNodeImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_XP_Explorer_LeafNode.gif");
                                        break;
                                    }
                            }
                        }

                        if (leafNodeImageUrl.Length != 0) {
                            leafNodeImageUrl = ResolveClientUrl(leafNodeImageUrl);
                        }
                        ImageUrls[index] = leafNodeImageUrl;
                        break;
                    case NoExpandImageIndex:
                        if (ShowLines) {
                            if (LineImagesFolder.Length == 0) {
                                ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_NoExpand.gif");
                            }
                            else {
                                ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "noexpand.gif"));
                            }
                        }
                        else {
                            if (NoExpandImageUrlInternal.Length > 0) {
                                ImageUrls[index] = ResolveClientUrl(NoExpandImageUrlInternal);
                            }
                            else if (LineImagesFolder.Length > 0) {
                                ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "noexpand.gif"));
                            }
                            else {
                                ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_NoExpand.gif");
                            }
                        }
                        break;

                    case PlusImageIndex:
                        if (ShowLines) {
                            if (LineImagesFolder.Length == 0) {
                                ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_Expand.gif");
                            }
                            else {
                                ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "plus.gif"));
                            }
                        }
                        else {
                            if (ExpandImageUrlInternal.Length > 0) {
                                ImageUrls[index] = ResolveClientUrl(ExpandImageUrlInternal);
                            }
                            else if (LineImagesFolder.Length > 0) {
                                ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "plus.gif"));
                            }
                            else {
                                ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_Expand.gif");
                            }
                        }
                        break;
                    case MinusImageIndex:
                        if (ShowLines) {
                            if (LineImagesFolder.Length == 0) {
                                ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_Collapse.gif");
                            }
                            else {
                                ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "minus.gif"));
                            }
                        }
                        else {
                            if (CollapseImageUrlInternal.Length > 0) {
                                ImageUrls[index] = ResolveClientUrl(CollapseImageUrlInternal);
                            }
                            else if (LineImagesFolder.Length > 0) {
                                ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "minus.gif"));
                            }
                            else {
                                ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_Collapse.gif");
                            }
                        }
                        break;
                    case IImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_I.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "i.gif"));
                        }
                        break;
                    case RImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_R.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "r.gif"));
                        }
                        break;
                    case RPlusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_RExpand.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "rplus.gif"));
                        }
                        break;
                    case RMinusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_RCollapse.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "rminus.gif"));
                        }
                        break;
                    case TImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_T.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "t.gif"));
                        }
                        break;
                    case TPlusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_TExpand.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "tplus.gif"));
                        }
                        break;
                    case TMinusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_TCollapse.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "tminus.gif"));
                        }
                        break;
                    case LImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_L.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "l.gif"));
                        }
                        break;
                    case LPlusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_LExpand.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "lplus.gif"));
                        }
                        break;
                    case LMinusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_LCollapse.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "lminus.gif"));
                        }
                        break;
                    case DashImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_Dash.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "dash.gif"));
                        }
                        break;
                    case DashPlusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_DashExpand.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "dashplus.gif"));
                        }
                        break;
                    case DashMinusImageIndex:
                        if (LineImagesFolder.Length == 0) {
                            ImageUrls[index] = Page.ClientScript.GetWebResourceUrl(typeof(TreeView), "TreeView_Default_DashCollapse.gif");
                        }
                        else {
                            ImageUrls[index] = ResolveClientUrl(UrlPath.SimpleCombine(LineImagesFolder, "dashminus.gif"));
                        }
                        break;
                }
            }

            return ImageUrls[index];
        }

        internal string GetLevelImageUrl(int index) {
            if (LevelImageUrls[index] == null) {
                string imageUrl = ((TreeNodeStyle)LevelStyles[index]).ImageUrl;
                if (imageUrl.Length > 0) {
                    LevelImageUrls[index] = ResolveClientUrl(imageUrl);
                }
                else {
                    LevelImageUrls[index] = String.Empty;
                }
            }

            return LevelImageUrls[index];
        }

        // After calling this, style1 has a merged class name,
        // and all properties explicitly set on style2 replace those on style1.
        // Also used by Menu
        internal static void GetMergedStyle(Style style1, Style style2) {
            string oldClass = style1.CssClass;
            style1.CopyFrom(style2);
            if (oldClass.Length != 0 && style2.CssClass.Length != 0) {
                style1.CssClass += ' ' + oldClass;
            }
        }

        private bool GetRenderClientScript(HttpBrowserCapabilities caps) {
            return (EnableClientScript &&
                    Enabled &&
                    (caps.EcmaScriptVersion.Major > 0) &&
                    (caps.W3CDomVersion.Major > 0) &&
                     !StringUtil.EqualsIgnoreCase(caps["tagwriter"], typeof(Html32TextWriter).FullName));
        }

        internal TreeNodeStyle GetStyle(TreeNode node) {
            if (node == null) {
                throw new ArgumentNullException("node");
            }

            bool parent = node.ChildNodes.Count != 0 || node.PopulateOnDemand;
            List<TreeNodeStyle> cache = parent ? CachedParentNodeStyles : CachedLeafNodeStyles;
            bool needsSelectedStyle = node.Selected && _selectedNodeStyle != null;

            int depth = node.Depth;
            TreeNodeStyle typedStyle = CacheGetItem<TreeNodeStyle>(cache, depth);

            if (!needsSelectedStyle && typedStyle != null) return typedStyle;

            if (typedStyle == null) {
                typedStyle = new TreeNodeStyle();
                typedStyle.CopyFrom(BaseTreeNodeStyle);

                if (_nodeStyle != null) {
                    GetMergedStyle(typedStyle, _nodeStyle);
                }

                if (depth == 0 && parent) {
                    if (_rootNodeStyle != null) {
                        GetMergedStyle(typedStyle, _rootNodeStyle);
                    }
                }
                else if (parent) {
                    if (_parentNodeStyle != null) {
                        GetMergedStyle(typedStyle, _parentNodeStyle);
                    }
                }
                else if (_leafNodeStyle != null) {
                    GetMergedStyle(typedStyle, _leafNodeStyle);
                }

                if (depth < LevelStyles.Count && LevelStyles[depth] != null) {
                    GetMergedStyle(typedStyle, LevelStyles[depth]);
                }

                CacheSetItem<TreeNodeStyle>(cache, depth, typedStyle);
            }


            if (needsSelectedStyle) {
                TreeNodeStyle selectedStyle = new TreeNodeStyle();
                selectedStyle.CopyFrom(typedStyle);
                GetMergedStyle(selectedStyle, _selectedNodeStyle);
                return selectedStyle;
            }
            return typedStyle;
        }

        private int GetTrailingIndex(string s) {
            int i = s.Length - 1;
            while (i > 0) {
                if (!Char.IsDigit(s[i])) {
                    break;
                }
                i--;
            }

            if ((i > -1) && (i < (s.Length - 1)) && ((s.Length - i) < 11)) {
                return Int32.Parse(s.Substring(i + 1), CultureInfo.InvariantCulture);
            }

            return -1;
        }

        internal static string Escape(string value) {
            // This function escapes \ and | to avoid collisions with the internal path separator.
            // Also used by Menu
            StringBuilder b = null;

            if (String.IsNullOrEmpty(value)) {
                return String.Empty;
            }

            int startIndex = 0;
            int count = 0;
            for (int i = 0; i < value.Length; i++) {
                switch (value[i]) {
                    case InternalPathSeparator:
                        if (b == null) {
                            b = new StringBuilder(value.Length + 5);
                        }

                        if (count > 0) {
                            b.Append(value, startIndex, count);
                        }

                        b.Append(EscapeSequenceForPathSeparator);

                        startIndex = i + 1;
                        count = 0;
                        break;
                    case EscapeCharacter:
                        if (b == null) {
                            b = new StringBuilder(value.Length + 5);
                        }

                        if (count > 0) {
                            b.Append(value, startIndex, count);
                        }

                        b.Append(EscapeSequenceForEscapeCharacter);

                        startIndex = i + 1;
                        count = 0;
                        break;
                    default:
                        count++;
                        break;
                }
            }

            if (b == null) {
                return value;
            }

            if (count > 0) {
                b.Append(value, startIndex, count);
            }

            return b.ToString();
        }

        internal static string UnEscape(string value) {
            // Also used by Menu
            return value.Replace(
                EscapeSequenceForPathSeparator, InternalPathSeparator.ToString()).Replace(
                EscapeSequenceForEscapeCharacter, EscapeCharacter.ToString());
        }

        /// <devdoc>
        ///     Loads a nodes state from the postback data.  Basically, there are expand state (which may have changed on the client) and
        ///     check state.  It also fills a dictionary of nodes that were populated on the client (and need to be populated on the server).
        /// </devdoc>
        private void LoadNodeState(TreeNode node, ref int index, string expandState, IDictionary populatedNodes, int selectedNodeIndex) {
            // Recursive method - prevent stack overflow.
            RuntimeHelpers.EnsureSufficientExecutionStack();

            // If our populatedNodes dictionary contains the index for the current node, that means
            // it was populated on the client-side and needs to have it's child node states also updated
            if (PopulateNodesFromClient && (populatedNodes != null)) {
                if (populatedNodes.Contains(index)) {
                    populatedNodes[index] = node;
                }
            }

            // If nothing was posted, selectedNodeIndex will be -1
            if (selectedNodeIndex != -1) {
                // When something was posted, update to the new selected node
                if (node.Selected && (index != selectedNodeIndex)) {
                    node.Selected = false;
                }

                if ((index == selectedNodeIndex) &&
                    ((node.SelectAction == TreeNodeSelectAction.Select) ||
                    (node.SelectAction == TreeNodeSelectAction.SelectExpand))) {

                    bool oldSelected = node.Selected;

                    node.Selected = true;

                    if (!oldSelected) {
                        _fireSelectedNodeChanged = true;
                    }
                }
            }
            else if (node.Selected) {
                // Otherwise, just reselect the old selected node
                SetSelectedNode(node);
            }

            // Check if the node's checked state has changed since the last postback
            // But only if the node has checkbox UI (VSWhidbey 421233)
            if (node.GetEffectiveShowCheckBox()) {
                bool originalChecked = node.Checked;
                string checkBoxFieldID = CreateNodeId(index) + "CheckBox";
                if ((Context.Request.Form[checkBoxFieldID] != null) ||
                    (Context.Request.QueryString[checkBoxFieldID] != null)) {
                    if (!node.Checked) {
                        node.Checked = true;
                    }
                    if (originalChecked != node.Checked) {
                        CheckedChangedNodes.Add(node);
                    }
                }
                else {
                    if (originalChecked && !node.PreserveChecked) {
                        if (node.Checked) {
                            node.Checked = false;
                        }
                    }

                    if (originalChecked != node.Checked) {
                        CheckedChangedNodes.Add(node);
                    }
                }
            }

            // Get the client-side expand state of the current node
            if ((Page != null) && (Page.RequestInternal != null) &&
                (expandState != null) &&
                (expandState.Length > index) &&
                (ShowExpandCollapse ||
                (node.SelectAction == TreeNodeSelectAction.Expand) ||
                (node.SelectAction == TreeNodeSelectAction.SelectExpand))) {

                char c = expandState[index];
                switch (c) {
                    case 'e':
                        node.Expanded = true;
                        break;
                    case 'c':
                        node.Expanded = false;
                        break;
                    //case 'n': case 'u':
                    //    break;
                }
            }

            index++;

            // If there were children for this node, load their states too
            TreeNodeCollection nodes = node.ChildNodes;
            if (nodes.Count > 0) {
                for (int i = 0; i < nodes.Count; i++) {
                    LoadNodeState(nodes[i], ref index, expandState, populatedNodes, selectedNodeIndex);
                }
            }
        }


        /// <internalonly/>
        /// <devdoc>
        /// Loads a saved state of the <see cref='System.Web.UI.WebControls.TreeView'/>.
        /// </devdoc>
        protected override void LoadViewState(object state) {
            if (state != null) {
                object[] savedState = (object[])state;

                if (savedState[0] != null) {
                    base.LoadViewState(savedState[0]);
                }

                if (savedState[1] != null) {
                    ((IStateManager)NodeStyle).LoadViewState(savedState[1]);
                }

                if (savedState[2] != null) {
                    ((IStateManager)RootNodeStyle).LoadViewState(savedState[2]);
                }

                if (savedState[3] != null) {
                    ((IStateManager)ParentNodeStyle).LoadViewState(savedState[3]);
                }

                if (savedState[4] != null) {
                    ((IStateManager)LeafNodeStyle).LoadViewState(savedState[4]);
                }

                if (savedState[5] != null) {
                    ((IStateManager)SelectedNodeStyle).LoadViewState(savedState[5]);
                }

                if (savedState[6] != null) {
                    ((IStateManager)HoverNodeStyle).LoadViewState(savedState[6]);
                }

                if (savedState[7] != null) {
                    ((IStateManager)LevelStyles).LoadViewState(savedState[7]);
                }

                if (savedState[8] != null) {
                    ((IStateManager)Nodes).LoadViewState(savedState[8]);
                }
            }
        }

        protected internal override void OnInit(EventArgs e) {
            ChildControlsCreated = true;
            base.OnInit(e);
        }

        protected virtual void OnTreeNodeCheckChanged(TreeNodeEventArgs e) {
            TreeNodeEventHandler handler = (TreeNodeEventHandler)Events[CheckChangedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        ///     Overridden to register for postback, and if client script is enabled, renders out
        ///     the necessary script and hidden field to function.
        /// </devdoc>
        protected internal override void OnPreRender(EventArgs e) {
            base.OnPreRender(e);

            EnsureRenderSettings();

            if (Page != null) {
                if (!Page.IsPostBack && !_dataBound) {
                    ExpandToDepth(Nodes, ExpandDepth);
                }

                Page.RegisterRequiresPostBack(this);

                // Build up a hidden field of the expand state of all nodes
                StringBuilder expandState = new StringBuilder();

                // We need to number all of the nodes, so call save node state.
                int index = 0;
                for (int i = 0; i < Nodes.Count; i++) {
                    SaveNodeState(Nodes[i], ref index, expandState, true);
                }

                if (RenderClientScript) {
                    ClientScriptManager scriptOM = Page.ClientScript;
                    scriptOM.RegisterHiddenField(this, ExpandStateID, expandState.ToString());

                    // Register all the images (including lines if necessary)
                    int imageCount = 6;
                    if (ShowLines) {
                        imageCount = 19;
                    }
                    for (int i = 0; i < imageCount; i++) {
                        string imageUrl = GetImageUrl(i);
                        if (imageUrl.Length > 0) {
                            imageUrl = Util.QuoteJScriptString(imageUrl);
                        }
                        scriptOM.RegisterArrayDeclaration(this, ImageArrayID, "'" + imageUrl + "'");
                    }

                    // Register a hidden field for tracking the selected node and save it in viewstate so we can fire changed events on postback
                    string selectedNodeID = String.Empty;
                    if (SelectedNode != null) {
                        // Validate that the selected node has not been removed
                        TreeNode node = SelectedNode;
                        while ((node != null) && (node != RootNode)) {
                            node = node.GetParentInternal();
                        }

                        if (node == RootNode) {
                            selectedNodeID = SelectedNode.SelectID;
                            ViewState["SelectedNode"] = SelectedNode.SelectID;
                        }
                        else {
                            ViewState["SelectedNode"] = null;
                        }
                    }
                    else {
                        ViewState["SelectedNode"] = null;
                    }

                    scriptOM.RegisterHiddenField(this, SelectedNodeFieldID, selectedNodeID);

                    // TreeView.js depends on WebForms.js so register that too.
                    Page.RegisterWebFormsScript();
                    // Register the external TreeView javascript file.
                    scriptOM.RegisterClientScriptResource(this, typeof(TreeView), "TreeView.js");

                    string clientDataObjectID = ClientDataObjectID;

                    string populateStartupScript = String.Empty;
                    if (PopulateNodesFromClient) {
                        // Remember the max index of the nodes, so we can properly restore client-populated nodes on postback
                        ViewState["LastIndex"] = index;

                        // Register a log for client-populated nodes
                        scriptOM.RegisterHiddenField(this, PopulateLogID, String.Empty);

                        populateStartupScript = clientDataObjectID + ".lastIndex = " + index + ";\r\n" +
                                                clientDataObjectID + ".populateLog = theForm.elements['" + PopulateLogID + "'];\r\n" +
                                                clientDataObjectID + ".treeViewID = '" + UniqueID + "';\r\n" +
                                                clientDataObjectID + ".name = '" + clientDataObjectID + "';\r\n";
                        // Using GetType() here instead of typeof because derived TreeViews might conflict
                        if (!scriptOM.IsClientScriptBlockRegistered(GetType(), "PopulateNode")) {
                            // 
                            scriptOM.RegisterClientScriptBlock(this, GetType(), "PopulateNode",
                            populateNodeScript +
                            scriptOM.GetCallbackEventReference("context.data.treeViewID", "param", "TreeView_ProcessNodeData",
                                                               "context", "TreeView_ProcessNodeData", false) +
                            populateNodeScriptEnd,
                            true /* add script tags */);
                        }
                    }
                    string selectedInfo = String.Empty;
                    if (_selectedNodeStyle != null) {
                        string className = _selectedNodeStyle.RegisteredCssClass;
                        if (className.Length > 0) {
                            className += " ";
                        }
                        string hyperLinkClassName = _selectedNodeStyle.HyperLinkStyle.RegisteredCssClass;
                        if (hyperLinkClassName.Length > 0) {
                            hyperLinkClassName += " ";
                        }
                        if (!String.IsNullOrEmpty(_selectedNodeStyle.CssClass)) {
                            string cssClass = _selectedNodeStyle.CssClass + " ";
                            className += cssClass;
                            hyperLinkClassName += cssClass;
                        }
                        selectedInfo = clientDataObjectID + ".selectedClass = '" + className + "';\r\n" +
                                       clientDataObjectID + ".selectedHyperLinkClass = '" + hyperLinkClassName + "';\r\n";
                    }

                    string hoverInfo = String.Empty;
                    if (EnableHover) {
                        string className = _hoverNodeStyle.RegisteredCssClass;
                        string hyperLinkClassName = _hoverNodeHyperLinkStyle.RegisteredCssClass;
                        if (!String.IsNullOrEmpty(_hoverNodeStyle.CssClass)) {
                            string cssClass = _hoverNodeStyle.CssClass;
                            if (!String.IsNullOrEmpty(className)) {
                                className += " ";
                            }
                            if (!String.IsNullOrEmpty(hyperLinkClassName)) {
                                hyperLinkClassName += " ";
                            }
                            className += cssClass;
                            hyperLinkClassName += cssClass;
                        }

                        selectedInfo = clientDataObjectID + ".hoverClass = '" + className + "';\r\n" +
                                       clientDataObjectID + ".hoverHyperLinkClass = '" + hyperLinkClassName + "';\r\n";
                    }

                    string createDataObjectScript = "var " + clientDataObjectID + " = new Object();\r\n" +
                                                    clientDataObjectID + ".images = " + ImageArrayID + ";\r\n" +
                                                    clientDataObjectID + ".collapseToolTip = \""
                                                        + Util.QuoteJScriptString(CollapseImageToolTip) + "\";\r\n" +
                                                    clientDataObjectID + ".expandToolTip = \""
                                                        + Util.QuoteJScriptString(ExpandImageToolTip) + "\";\r\n" +
                                                    clientDataObjectID + ".expandState = theForm.elements['" + ExpandStateID + "'];\r\n" +
                                                    clientDataObjectID + ".selectedNodeID = theForm.elements['" + SelectedNodeFieldID + "'];\r\n" +
                                                    selectedInfo +
                                                    hoverInfo +
                                                    "(function() {\r\n  for (var i=0;i<" + imageCount + ";i++) {\r\n" +
                                                    "  var preLoad = new Image();\r\n" +
                                                    "  if (" + ImageArrayID + "[i].length > 0)\r\n" +
                                                    "    preLoad.src = " + ImageArrayID + "[i];\r\n" +
                                                    "  }\r\n})();\r\n" + populateStartupScript;

                    // Register a startup script that creates a tree data object
                    // Note: the first line is to prevent Firefox warnings on undeclared identifiers, needed if a user event occurs
                    // before all startup scripts have run.
                    scriptOM.RegisterClientScriptBlock(this, GetType(), ClientID + "_CreateDataObject1", "var " + clientDataObjectID + " = null;", true);
                    scriptOM.RegisterStartupScript(this, GetType(), ClientID + "_CreateDataObject2", createDataObjectScript, true);

                    // DevDiv 95670: Delete circular reference to prevent IE memory leaks during partial update
                    IScriptManager scriptManager = Page.ScriptManager;
                    if ((scriptManager != null) && scriptManager.SupportsPartialRendering) {
                        scriptManager.RegisterDispose(this, ImageArrayID + ".length = 0;\r\n" + clientDataObjectID + " = null;");
                    }
                }
            }
        }

        protected virtual void OnSelectedNodeChanged(EventArgs e) {
            EventHandler handler = (EventHandler)Events[SelectedNodeChangedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnTreeNodeCollapsed(TreeNodeEventArgs e) {
            TreeNodeEventHandler handler = (TreeNodeEventHandler)Events[TreeNodeCollapsedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnTreeNodeExpanded(TreeNodeEventArgs e) {
            TreeNodeEventHandler handler = (TreeNodeEventHandler)Events[TreeNodeExpandedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnTreeNodeDataBound(TreeNodeEventArgs e) {
            TreeNodeEventHandler handler = (TreeNodeEventHandler)Events[TreeNodeDataBoundEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnTreeNodePopulate(TreeNodeEventArgs e) {
            TreeNodeEventHandler handler = (TreeNodeEventHandler)Events[TreeNodePopulateEvent];
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        ///     Overridden to create all the tree nodes based on the datasource provided
        /// </devdoc>
        protected internal override void PerformDataBinding() {
            base.PerformDataBinding();

            // This is to treat the case where the tree has already been bound
            // but the data source was removed and we're rebinding (we want to get an emty tree)
            if (!DesignMode && _dataBound &&
                String.IsNullOrEmpty(DataSourceID) && DataSource == null) {

                Nodes.Clear();
                return;
            }

            DataBindNode(RootNode);

            if (!String.IsNullOrEmpty(DataSourceID) || DataSource != null) {
                _dataBound = true;
            }

            // Always expand depth if data is changed
            ExpandToDepth(Nodes, ExpandDepth);
        }


        /// <devdoc>
        ///     Triggers a populate event for the specified node
        /// </devdoc>
        internal void PopulateNode(TreeNode node) {
            if (node.DataBound) {
                DataBindNode(node);
            }
            else {
                OnTreeNodePopulate(new TreeNodeEventArgs(node));
            }
            node.Populated = true;
            node.PopulateOnDemand = false;
        }

        internal void RaiseSelectedNodeChanged() {
            OnSelectedNodeChanged(EventArgs.Empty);
        }


        internal void RaiseTreeNodeCollapsed(TreeNode node) {
            OnTreeNodeCollapsed(new TreeNodeEventArgs(node));
        }


        internal void RaiseTreeNodeExpanded(TreeNode node) {
            OnTreeNodeExpanded(new TreeNodeEventArgs(node));
        }

        private void RegisterStyle(Style style) {
            if (style.IsEmpty) {
                return;
            }

            if (Page != null && Page.SupportsStyleSheets) {
                string name = ClientID + "_" + _cssStyleIndex++.ToString(NumberFormatInfo.InvariantInfo);
                Page.Header.StyleSheet.CreateStyleRule(style, this, "." + name);
                style.SetRegisteredCssClass(name);
            }
        }

        public override void RenderBeginTag(HtmlTextWriter writer) {
            ControlRenderingHelper.WriteSkipLinkStart(writer, RenderingCompatibility, DesignMode, SkipLinkText, SpacerImageUrl, ClientID);

            base.RenderBeginTag(writer);

            if (DesignMode) {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
            }
        }


        /// <devdoc>
        ///     Overridden to render all the tree nodes
        /// </devdoc>
        protected internal override void RenderContents(HtmlTextWriter writer) {
            base.RenderContents(writer);

            // Make sure we are in a form tag with runat=server.
            if (Page != null) {
                Page.VerifyRenderingInServerForm(this);
            }

            bool enabled = IsEnabled;

            // Render all the root nodes and have them render their children recursively
            for (int i = 0; i < Nodes.Count; i++) {
                TreeNode node = Nodes[i];
                bool[] isLast = new bool[10];
                isLast[0] = (i == (Nodes.Count - 1));
                node.Render(writer, i, isLast, enabled);
            }

            // Reset all these cached values so things can pick up changes in the designer
            if (DesignMode) {
                // Reset all these cached values so things can pick up changes in the designer
                if (_nodeStyle != null) {
                    _nodeStyle.ResetCachedStyles();
                }
                if (_leafNodeStyle != null) {
                    _leafNodeStyle.ResetCachedStyles();
                }
                if (_parentNodeStyle != null) {
                    _parentNodeStyle.ResetCachedStyles();
                }
                if (_rootNodeStyle != null) {
                    _rootNodeStyle.ResetCachedStyles();
                }
                if (_selectedNodeStyle != null) {
                    _selectedNodeStyle.ResetCachedStyles();
                }
                if (_hoverNodeStyle != null) {
                    _hoverNodeHyperLinkStyle = new HyperLinkStyle(_hoverNodeStyle);
                }

                foreach (TreeNodeStyle style in LevelStyles) {
                    style.ResetCachedStyles();
                }

                if (_imageUrls != null) {
                    for (int i = 0; i < _imageUrls.Length; i++) {
                        _imageUrls[i] = null;
                    }
                }

                _cachedExpandImageUrl = null;
                _cachedCollapseImageUrl = null;
                _cachedNoExpandImageUrl = null;
                _cachedLeafNodeClassNames = null;
                _cachedLeafNodeHyperLinkClassNames = null;
                _cachedLeafNodeStyles = null;
                _cachedLevelsContainingCssClass = null;
                _cachedParentNodeClassNames = null;
                _cachedParentNodeHyperLinkClassNames = null;
                _cachedParentNodeStyles = null;
            }
        }

        public override void RenderEndTag(HtmlTextWriter writer) {
            if (DesignMode) {
                writer.RenderEndTag();
                writer.RenderEndTag();
            }

            base.RenderEndTag(writer);

            ControlRenderingHelper.WriteSkipLinkEnd(writer, DesignMode, SkipLinkText, ClientID);
        }


        /// <devdoc>
        ///     Saves the expand state of nodes.  The value is placed into a hidden field on the page
        ///     which gets updated on the client as nodes are expanded and collapsed.  This also
        ///     numbers the nodes, which provides IDs for the nodes.
        /// </devdoc>
        private void SaveNodeState(TreeNode node, ref int index, StringBuilder expandState, bool rendered) {
            // Set the index for the current node
            node.Index = index++;

            // If we aren't using client script, some checked nodes might not get rendered, and hence,
            // won't postback their checked state.  We need to store some viewstate for those.
            if (node.CheckedSet) {
                if (!Enabled || (!RenderClientScript && !rendered && node.Checked)) {
                    node.PreserveChecked = true;
                }
                else {
                    node.PreserveChecked = false;
                }
            }

            if (node.PopulateOnDemand) {
                if ((node.ChildNodes.Count == 0) || (node.Expanded != true)) {
                    // If the node is to be populated on the client and there are no children or it
                    // has children and is not expanded, it's a collpased node ('c')
                    expandState.Append('c');
                }
                else {
                    // Otherwise, it's an expanded node
                    expandState.Append('e');
                }
            }
            else if (node.ChildNodes.Count == 0) {
                // If there aren't any child nodes, then it's a normal node
                expandState.Append('n');
            }
            else {
                if (node.Expanded == null) {
                    expandState.Append('u');
                }
                else if (node.Expanded == true) {
                    // If it has children and it's expanded, it's expanded
                    expandState.Append('e');
                }
                else {
                    // If it has children and it isn't expanded, it's collapsed
                    expandState.Append('c');
                }
            }

            // If there are children, save their state too
            if (node.ChildNodes.Count > 0) {
                TreeNodeCollection nodes = node.ChildNodes;
                for (int i = 0; i < nodes.Count; i++) {
                    SaveNodeState(nodes[i], ref index, expandState, (node.Expanded == true) && rendered);
                }
            }
        }


        /// <internalonly/>
        /// <devdoc>
        ///  Saves the state of the <see cref='System.Web.UI.WebControls.TreeView'/>.
        /// </devdoc>
        protected override object SaveViewState() {
            // If the tree is invisible (or one of its parents is) and we're in the GET request, we have to remember (VSWhidbey 349279)
            // 


            if (!Visible && (Page != null) && !Page.IsPostBack) {
                ViewState["NeverExpanded"] = true;
            }

            object[] state = new object[9];

            state[0] = base.SaveViewState();

            bool hasViewState = (state[0] != null);

            if (_nodeStyle != null) {
                state[1] = ((IStateManager)_nodeStyle).SaveViewState();
                hasViewState |= (state[1] != null);
            }

            if (_rootNodeStyle != null) {
                state[2] = ((IStateManager)_rootNodeStyle).SaveViewState();
                hasViewState |= (state[2] != null);
            }

            if (_parentNodeStyle != null) {
                state[3] = ((IStateManager)_parentNodeStyle).SaveViewState();
                hasViewState |= (state[3] != null);
            }

            if (_leafNodeStyle != null) {
                state[4] = ((IStateManager)_leafNodeStyle).SaveViewState();
                hasViewState |= (state[4] != null);
            }

            if (_selectedNodeStyle != null) {
                state[5] = ((IStateManager)_selectedNodeStyle).SaveViewState();
                hasViewState |= (state[5] != null);
            }

            if (_hoverNodeStyle != null) {
                state[6] = ((IStateManager)_hoverNodeStyle).SaveViewState();
                hasViewState |= (state[6] != null);
            }

            if (_levelStyles != null) {
                state[7] = ((IStateManager)_levelStyles).SaveViewState();
                hasViewState |= (state[7] != null);
            }

            state[8] = ((IStateManager)Nodes).SaveViewState();
            hasViewState |= (state[8] != null);

            if (hasViewState) {
                return state;
            }
            else {
                return null;
            }
        }


        /// <devdoc>
        /// Allows a derived TreeView to set the DataBound proprety on a node
        /// </devdoc>
        protected void SetNodeDataBound(TreeNode node, bool dataBound) {
            node.SetDataBound(dataBound);
        }


        /// <devdoc>
        /// Allows a derived TreeView to set the DataItem on a node
        /// </devdoc>
        protected void SetNodeDataItem(TreeNode node, object dataItem) {
            node.SetDataItem(dataItem);
        }


        /// <devdoc>
        /// Allows a derived TreeView to set the DataPath on a node
        /// </devdoc>
        protected void SetNodeDataPath(TreeNode node, string dataPath) {
            node.SetDataPath(dataPath);
        }

        internal void SetSelectedNode(TreeNode node) {
            Debug.Assert(node == null || node.Owner == this);

            if (_selectedNode != node) {
                // Unselect the previously selected node
                if ((_selectedNode != null) && (_selectedNode.Selected)) {
                    _selectedNode.SetSelected(false);
                }
                _selectedNode = node;
                // Notify the new selected node that it's now selected
                if ((_selectedNode != null) && !_selectedNode.Selected) {
                    _selectedNode.SetSelected(true);
                }
            }
        }


        /// <internalonly/>
        /// <devdoc>
        ///    Marks the starting point to begin tracking and saving changes to the
        ///    control as part of the control viewstate.
        /// </devdoc>
        protected override void TrackViewState() {
            base.TrackViewState();
            if (_nodeStyle != null) {
                ((IStateManager)_nodeStyle).TrackViewState();
            }

            if (_rootNodeStyle != null) {
                ((IStateManager)_rootNodeStyle).TrackViewState();
            }

            if (_parentNodeStyle != null) {
                ((IStateManager)_parentNodeStyle).TrackViewState();
            }

            if (_leafNodeStyle != null) {
                ((IStateManager)_leafNodeStyle).TrackViewState();
            }

            if (_selectedNodeStyle != null) {
                ((IStateManager)_selectedNodeStyle).TrackViewState();
            }

            if (_hoverNodeStyle != null) {
                ((IStateManager)_hoverNodeStyle).TrackViewState();
            }

            if (_levelStyles != null) {
                ((IStateManager)_levelStyles).TrackViewState();
            }

            if (_bindings != null) {
                ((IStateManager)_bindings).TrackViewState();
            }

            ((IStateManager)Nodes).TrackViewState();
        }

        #region IPostBackEventHandler implementation

        /// <internalonly/>
        void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) {
            RaisePostBackEvent(eventArgument);
        }

        protected virtual void RaisePostBackEvent(string eventArgument) {
            ValidateEvent(UniqueID, eventArgument);

            // Do not take any postback into account if the tree is disabled.
            if (!IsEnabled) return;

            if (AdapterInternal != null) {
                IPostBackEventHandler pbeh = AdapterInternal as IPostBackEventHandler;
                if (pbeh != null) {
                    pbeh.RaisePostBackEvent(eventArgument);
                }
            }
            else {
                if (eventArgument.Length == 0) {
                    return;
                }

                // On postback, see what kind of event we received by checking the first character
                char eventType = eventArgument[0];
                // Get the path of the node specified in the eventArgument
                string nodePath = HttpUtility.HtmlDecode(eventArgument.Substring(1));
                // Find that node in the tree
                TreeNode node = Nodes.FindNode(nodePath.Split(InternalPathSeparator), 0);

                if (node != null) {
                    switch (eventType) {
                        case 't': {
                                // 't' means that we're toggling the expand state of the node
                                if (ShowExpandCollapse ||
                                    (node.SelectAction == TreeNodeSelectAction.Expand) ||
                                    (node.SelectAction == TreeNodeSelectAction.SelectExpand)) {

                                    node.ToggleExpandState();
                                }
                                break;
                            }
                        case 's': {
                                // 's' means that the node has been selected
                                if ((node.SelectAction == TreeNodeSelectAction.Expand) || (node.SelectAction == TreeNodeSelectAction.SelectExpand)) {
                                    if (node.Expanded != true) {
                                        node.Expanded = true;
                                    }
                                    else if (node.SelectAction == TreeNodeSelectAction.Expand) {
                                        // Expand is really just toggle expand state (while SelectExpand is just expand)
                                        node.Expanded = false;
                                    }
                                }

                                if ((node.SelectAction == TreeNodeSelectAction.Select) || (node.SelectAction == TreeNodeSelectAction.SelectExpand)) {
                                    bool selectedChanged = false;
                                    if (!node.Selected) {
                                        selectedChanged = true;
                                    }

                                    node.Selected = true;

                                    if (selectedChanged) {
                                        _fireSelectedNodeChanged = true;
                                    }
                                }
                                break;
                            }
                    }
                }

                if (_fireSelectedNodeChanged) {
                    try {
                        RaiseSelectedNodeChanged();
                    }
                    finally {
                        _fireSelectedNodeChanged = false;
                    }
                }
            }
        }
        #endregion

        #region ICallbackEventHandler implementation

        /// <internalonly/>
        void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) {
            RaiseCallbackEvent(eventArgument);
        }

        string ICallbackEventHandler.GetCallbackResult() {
            return GetCallbackResult();
        }

        protected virtual void RaiseCallbackEvent(string eventArgument) {
            _callbackEventArgument = eventArgument;
        }

        protected virtual string GetCallbackResult() {
            // Do not take any callback into account if the tree is disabled.
            if (!IsEnabled) return String.Empty;

            // Split the eventArgument into pieces
            // The format is (without the spaces):
            // nodeIndex | lastIndex | databound | parentIsLast | text.length | text datapath.Length | datapath path

            // The first piece is always the node index
            int startIndex = 0;
            int endIndex = _callbackEventArgument.IndexOf('|');
            string nodeIndexString = _callbackEventArgument.Substring(startIndex, endIndex);
            int nodeIndex = Int32.Parse(nodeIndexString, CultureInfo.InvariantCulture);

            // The second piece is always the last index
            startIndex = endIndex + 1;
            endIndex = _callbackEventArgument.IndexOf('|', startIndex);
            int lastIndex = Int32.Parse(_callbackEventArgument.Substring(startIndex, endIndex - startIndex), CultureInfo.InvariantCulture);

            // The third piece is always the last databound bool followed by the checked bool
            bool dataBound = (_callbackEventArgument[endIndex + 1] == 't');
            bool nodeChecked = (_callbackEventArgument[endIndex + 2] == 't');

            // Fourth is the parentIsLast array
            startIndex = endIndex + 3;
            endIndex = _callbackEventArgument.IndexOf('|', startIndex);
            string parentIsLast = _callbackEventArgument.Substring(startIndex, endIndex - startIndex);

            // Fifth is the node text
            startIndex = endIndex + 1;
            endIndex = _callbackEventArgument.IndexOf('|', startIndex);
            int nodeTextLength = Int32.Parse(_callbackEventArgument.Substring(startIndex, endIndex - startIndex), CultureInfo.InvariantCulture);
            startIndex = endIndex + 1;
            endIndex = startIndex + nodeTextLength;
            string nodeText = _callbackEventArgument.Substring(startIndex, endIndex - startIndex);

            // Sixth is the data path
            startIndex = endIndex;
            endIndex = _callbackEventArgument.IndexOf('|', startIndex);
            int dataPathLength = Int32.Parse(_callbackEventArgument.Substring(startIndex, endIndex - startIndex), CultureInfo.InvariantCulture);
            startIndex = endIndex + 1;
            endIndex = startIndex + dataPathLength;
            string dataPath = _callbackEventArgument.Substring(startIndex, endIndex - startIndex);

            // Last piece is the value path
            startIndex = endIndex;
            string valuePath = _callbackEventArgument.Substring(startIndex);

            // Last piece of the value path is the node value
            startIndex = valuePath.LastIndexOf(InternalPathSeparator);
            string nodeValue = TreeView.UnEscape(valuePath.Substring(startIndex + 1));

            // Validate that input for forged callbacks
            ValidateEvent(UniqueID,
                String.Concat(nodeIndexString, nodeText, valuePath, dataPath));

            TreeNode node = CreateNode();
            node.PopulateOnDemand = true;
            if (nodeText != null && nodeText.Length != 0) {
                node.Text = nodeText;
            }
            if (nodeValue != null && nodeValue.Length != 0) {
                node.Value = nodeValue;
            }
            node.SetDataBound(dataBound);
            node.Checked = nodeChecked;
            node.SetPath(valuePath);
            node.SetDataPath(dataPath);
            PopulateNode(node);

            string result = String.Empty;
            if (node.ChildNodes.Count > 0) {
                // Get the expand state for all the nodes (like we do in OnPreRender)
                StringBuilder expandState = new StringBuilder();
                for (int i = 0; i < node.ChildNodes.Count; i++) {
                    SaveNodeState(node.ChildNodes[i], ref lastIndex, expandState, true);
                }

                StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                // 
                HtmlTextWriter writer = new HtmlTextWriter(stringWriter);

                int depth = node.Depth;
                bool[] isLast = new bool[depth + 5];
                if (parentIsLast.Length > 0) {
                    // Restore the isLast bool array so we can properly draw the lines
                    for (int i = 0; i < parentIsLast.Length; i++) {
                        if (parentIsLast[i] == 't') {
                            isLast[i] = true;
                        }
                    }
                }

                EnsureRenderSettings();

                // Render out the child nodes
                if (node.Expanded != true) {
                    writer.AddStyleAttribute("display", "none");
                }
                writer.AddAttribute(HtmlTextWriterAttribute.Id, CreateNodeId(nodeIndex) + "Nodes");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                node.RenderChildNodes(writer, depth, isLast, true);
                writer.RenderEndTag();
                writer.Flush();
                writer.Close();

                result = lastIndex.ToString(CultureInfo.InvariantCulture) + "|" + expandState.ToString() + "|" + stringWriter.ToString();
            }

            _callbackEventArgument = String.Empty;
            return result;
        }
        #endregion

        #region IPostBackDataHandler implementation

        /// <internalonly/>
        bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) {
            return LoadPostData(postDataKey, postCollection);
        }

        protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) {
            // Do not take any postback into account if the tree is disabled.
            if (!IsEnabled) return false;

            int selectedNodeIndex = -1;

            string postedSelectedNodeID = postCollection[SelectedNodeFieldID];
            if (!String.IsNullOrEmpty(postedSelectedNodeID)) {
                selectedNodeIndex = GetTrailingIndex(postedSelectedNodeID);
            }

            _loadingNodeState = true;
            try {
                Dictionary<int, TreeNode> populatedNodes = null;
                int[] logList = null;
                int logLength = -1;
                // If we're populating on the client, we need to repopulate the nodes that were
                // populated on the client, so add all the node indexes that were populated on the client
                if (PopulateNodesFromClient) {
                    string log = postCollection[PopulateLogID];
                    if (log != null) {
                        string[] logParts = log.Split(',');
                        logLength = logParts.Length;
                        populatedNodes = new Dictionary<int, TreeNode>(Math.Min(logLength, 16)); // don't eagerly allocate the maximum dictionary size
                        logList = new int[logLength];
                        for (int i = 0; i < logLength; i++) {
                            if (logParts[i].Length > 0) {
                                int populateIndex = Int32.Parse(logParts[i], NumberStyles.Integer, CultureInfo.InvariantCulture);
                                if (populateIndex >= 0 && !populatedNodes.ContainsKey(populateIndex)) {
                                    logList[i] = populateIndex;
                                    // Putting null, which will be replaced during LoadNodeState
                                    populatedNodes.Add(populateIndex, null);
                                }
                                else {
                                    logList[i] = -1;
                                }
                            }
                            else {
                                logList[i] = -1;
                            }
                        }
                    }
                }

                // Make sure all the nodes that were checked on the client get checked
                // and restore the expand state of all those nodes.  Also, fill in the populatedNodes dictionary
                // with the actual TreeNode instances
                string expandState = postCollection[ExpandStateID];
                int index = 0;
                for (int i = 0; i < Nodes.Count; i++) {
                    LoadNodeState(Nodes[i], ref index, expandState, populatedNodes, selectedNodeIndex);
                }

                // Now that the populatedNodes dictionary is filled in with TreeNode objects, we need
                // to call populate on those nodes.
                if (PopulateNodesFromClient && (logLength > 0)) {
                    object oLastIndex = ViewState["LastIndex"];
                    int lastIndex = (oLastIndex != null) ? (int)oLastIndex : -1;
                    for (int i = 0; i < logLength; i++) {
                        index = logList[i];
                        if ((index >= 0) && populatedNodes.ContainsKey(index)) {
                            TreeNode node = populatedNodes[index];
                            if (node != null) {
                                PopulateNode(node);

                                // Since the just-populated nodes could have been expanded and populated on the client as well,
                                // we need to load the node state of those nodes (filling in the populatedNodes dictionary with
                                // those TreeNode instances
                                if ((node.ChildNodes.Count > 0) && (lastIndex != -1)) {
                                    TreeNodeCollection nodes = node.ChildNodes;
                                    for (int j = 0; j < nodes.Count; j++) {
                                        LoadNodeState(nodes[j], ref lastIndex, expandState, populatedNodes, selectedNodeIndex);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally {
                _loadingNodeState = false;
            }

            return (_checkedChangedNodes != null);
        }


        /// <internalonly/>
        void IPostBackDataHandler.RaisePostDataChangedEvent() {
            RaisePostDataChangedEvent();
        }

        protected virtual void RaisePostDataChangedEvent() {
            // If there were nodes whose check state has changed, fire events for each one
            if (_checkedChangedNodes != null) {
                foreach (TreeNode node in _checkedChangedNodes) {
                    OnTreeNodeCheckChanged(new TreeNodeEventArgs(node));
                }
            }
        }
        #endregion

        private class TreeViewExpandDepthConverter : Int32Converter {
            private const string fullyExpandedString = "FullyExpand";
            private static object[] expandDepthValues = { -1,
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                21, 22, 23, 24, 25, 26, 27, 28, 29, 30};

            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
                if (sourceType == typeof(string)) {
                    return true;
                }

                return base.CanConvertFrom(context, sourceType);
            }

            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
                if (destinationType == typeof(int)) {
                    return true;
                }
                else if (destinationType == typeof(string)) {
                    return true;
                }

                return base.CanConvertTo(context, destinationType);
            }


            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
                string strValue = value as string;
                if (strValue != null) {
                    if (String.Equals(strValue, fullyExpandedString, StringComparison.OrdinalIgnoreCase)) {
                        return -1;
                    }
                }

                return base.ConvertFrom(context, culture, value);
            }

            public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
                if (destinationType == typeof(string)) {
                    if ((value is int) && ((int)value == -1)) {
                        return fullyExpandedString;
                    }

                    string strValue = value as string;
                    if (strValue != null) {
                        if (String.Equals(strValue, fullyExpandedString, StringComparison.OrdinalIgnoreCase)) {
                            return value;
                        }
                    }
                }
                else if (destinationType == typeof(int)) {
                    string strValue = value as string;
                    if (strValue != null) {
                        if (String.Equals(strValue, fullyExpandedString, StringComparison.OrdinalIgnoreCase)) {
                            return -1;
                        }
                    }
                }

                return base.ConvertTo(context, culture, value, destinationType);
            }

            public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
                return new StandardValuesCollection(expandDepthValues);
            }

            public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
                return true;
            }
        }
    }
}