File: ListView.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 (3525 lines) | stat: -rw-r--r-- 140,878 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
3518
3519
3520
3521
3522
3523
3524
3525
//------------------------------------------------------------------------------
// <copyright file="ListView.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Web.Resources;
using System.Web.UI.HtmlControls;
using System.Web.Util;


namespace System.Web.UI.WebControls {

    [DefaultProperty("SelectedValue")]
    [Designer("System.Web.UI.Design.WebControls.ListViewDesigner, " + AssemblyRef.SystemWebExtensionsDesign)]
    [ControlValueProperty("SelectedValue")]
    [DefaultEvent("SelectedIndexChanged")]
    [SupportsEventValidation]
    [ToolboxBitmap(typeof(ListView), "ListView.bmp")]
    [DataKeyProperty("SelectedPersistedDataKey")]
    public class ListView : DataBoundControl, INamingContainer, IPageableItemContainer, IPersistedSelector, IDataKeysControl, IDataBoundListControl, IWizardSideBarListControl {
        internal const string ItemCountViewStateKey = "_!ItemCount";

        private ITemplate _itemTemplate;
        private ITemplate _editItemTemplate;
        private ITemplate _insertItemTemplate;
        private ITemplate _layoutTemplate;
        private ITemplate _selectedItemTemplate;
        private ITemplate _groupTemplate;
        private ITemplate _itemSeparatorTemplate;
        private ITemplate _groupSeparatorTemplate;
        private ITemplate _emptyItemTemplate;
        private ITemplate _emptyDataTemplate;
        private ITemplate _alternatingItemTemplate;

        private static readonly object EventTotalRowCountAvailable = new object();
        private static readonly object EventPagePropertiesChanged = new object();
        private static readonly object EventPagePropertiesChanging = new object();
        private static readonly object EventItemCanceling = new object();
        private static readonly object EventItemCommand = new object();
        private static readonly object EventItemCreated = new object();
        private static readonly object EventItemDataBound = new object();
        private static readonly object EventItemDeleted = new object();
        private static readonly object EventItemDeleting = new object();
        private static readonly object EventItemEditing = new object();
        private static readonly object EventItemInserted = new object();
        private static readonly object EventItemInserting = new object();
        private static readonly object EventItemUpdated = new object();
        private static readonly object EventItemUpdating = new object();
        private static readonly object EventLayoutCreated = new object();
        private static readonly object EventSelectedIndexChanging = new object();
        private static readonly object EventSelectedIndexChanged = new object();
        private static readonly object EventSorted = new object();
        private static readonly object EventSorting = new object();
        private static readonly object EventWizardListItemDataBound = new object();

        private bool _performingSelect;
        private int _editIndex = -1;
        private int _selectedIndex = -1;
        private int _groupItemCount = 1;
        private string _modelValidationGroup;
        private string _sortExpression = String.Empty;
        private SortDirection _sortDirection = SortDirection.Ascending;

        private int _startRowIndex = 0;
        private int _maximumRows = -1;
        private int _totalRowCount = -1;

        private IList<ListViewDataItem> _itemList;
        private ListViewItem _insertItem;

        private string[] _dataKeyNames;
        private string[] _clientIDRowSuffix;
        private DataKeyArray _dataKeyArray;
        private ArrayList _dataKeysArrayList;
        private DataKeyArray _clientIDRowSuffixArray;
        private ArrayList _clientIDRowSuffixArrayList;
        private OrderedDictionary _boundFieldValues;
        private DataKey _persistedDataKey;

        private int _deletedItemIndex;
        private IOrderedDictionary _deleteKeys;
        private IOrderedDictionary _deleteValues;
        private IOrderedDictionary _insertValues;
        private IOrderedDictionary _updateKeys;
        private IOrderedDictionary _updateOldValues;
        private IOrderedDictionary _updateNewValues;

        private int _autoIDIndex = 0;
        private const string _automaticIDPrefix = "ctrl";

        private bool _instantiatedEmptyDataTemplate = false;

        // Keep track of where we instantiated templates when we're not using grouping
        private int _noGroupsOriginalIndexOfItemPlaceholderInContainer = -1;
        private int _noGroupsItemCreatedCount;
        private Control _noGroupsItemPlaceholderContainer;

        // Keep track of where we instantiated templates when we're using grouping
        private int _groupsOriginalIndexOfGroupPlaceholderInContainer = -1;
        private int _groupsItemCreatedCount;
        private Control _groupsGroupPlaceholderContainer;

        private string _updateMethod;
        private string _insertMethod;
        private string _deleteMethod;

        public ListView() {
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override string AccessKey {
            get {
                return base.AccessKey;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewDataItem), BindingDirection.TwoWay),
        ResourceDescription("ListView_AlternatingItemTemplate")
        ]
        public virtual ITemplate AlternatingItemTemplate {
            get {
                return _alternatingItemTemplate;
            }
            set {
                _alternatingItemTemplate = value;
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override Color BackColor {
            get {
                return base.BackColor;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override Color BorderColor {
            get {
                return base.BorderColor;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }


        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override Unit BorderWidth {
            get {
                return base.BorderWidth;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }


        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override BorderStyle BorderStyle {
            get {
                return base.BorderStyle;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        private IOrderedDictionary BoundFieldValues {
            get {
                if (_boundFieldValues == null) {
                    _boundFieldValues = new OrderedDictionary();
                }
                return _boundFieldValues;
            }
        }

        public override ControlCollection Controls {
            get {
                EnsureChildControls();
                return base.Controls;
            }
        }

        /// <devdoc>
        ///    <para>Gets or sets the property that determines whether the control treats empty string as
        ///    null when the item values are extracted.</para>
        /// </devdoc>
        [
        Category("Behavior"),
        DefaultValue(true),
        ResourceDescription("ListView_ConvertEmptyStringToNull"),
        ]
        public virtual bool ConvertEmptyStringToNull {
            get {
                object o = ViewState["ConvertEmptyStringToNull"];
                if (o != null) {
                    return (bool)o;
                }
                return true;
            }
            set {
                ViewState["ConvertEmptyStringToNull"] = value;
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never),
        CssClassPropertyAttribute
        ]
        public override string CssClass {
            get {
                return base.CssClass;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        /// <devdoc>
        /// An array of ordered dictionaries that represents each key
        /// </devdoc>
        private ArrayList DataKeysArrayList {
            get {
                if (_dataKeysArrayList == null) {
                    _dataKeysArrayList = new ArrayList();
                }
                return _dataKeysArrayList;
            }
        }

        private ArrayList ClientIDRowSuffixArrayList {
            get {
                if (_clientIDRowSuffixArrayList == null) {
                    _clientIDRowSuffixArrayList = new ArrayList();
                }
                return _clientIDRowSuffixArrayList;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResourceDescription("ListView_DataKeys")
        ]
        public virtual DataKeyArray DataKeys {
            get {
                if (_dataKeyArray == null) {
                    _dataKeyArray = new DataKeyArray(this.DataKeysArrayList);
                    if (IsTrackingViewState)
                        ((IStateManager)_dataKeyArray).TrackViewState();
                }
                return _dataKeyArray;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID"),
        ]
        public DataKeyArray ClientIDRowSuffixDataKeys {
            get {
                if (_clientIDRowSuffixArray == null) {
                    _clientIDRowSuffixArray = new DataKeyArray(this.ClientIDRowSuffixArrayList);
                }
                return _clientIDRowSuffixArray;
            }
        }

        [
        DefaultValue(null),
        Editor("System.Web.UI.Design.WebControls.DataFieldEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        Category("Data"),
        ResourceDescription("ListView_DataKeyNames"),
        SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
                        Justification = "Required by ASP.NET parser."),
        TypeConverterAttribute(typeof(StringArrayConverter)),
        ]
        public virtual string[] DataKeyNames {
            get {
                object o = _dataKeyNames;
                if (o != null) {
                    return (string[])((string[])o).Clone();
                }
                return new string[0];
            }
            set {
                if (!DataBoundControlHelper.CompareStringArrays(value, DataKeyNamesInternal)) {
                    if (value != null) {
                        _dataKeyNames = (string[])value.Clone();
                    }
                    else {
                        _dataKeyNames = null;
                    }

                    ClearDataKeys();
                    SetRequiresDataBindingIfInitialized();
                }
            }
        }

        // This version doesn't clone the array
        private string[] DataKeyNamesInternal {
            get {
                object o = _dataKeyNames;
                if (o != null) {
                    return (string[])o;
                }
                return new string[0];
            }
        }


        [
        Category("Default"),
        DefaultValue(-1),
        ResourceDescription("ListView_EditIndex")
        ]
        public virtual int EditIndex {
            get {
                return _editIndex;
            }
            set {
                if (value < -1) {
                    throw new ArgumentOutOfRangeException("value");
                }
                if (value != _editIndex) {
                    if (value == -1) {
                        BoundFieldValues.Clear();
                    }
                    _editIndex = value;
                    SetRequiresDataBindingIfInitialized();
                }
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResourceDescription("ListView_EditItem")
        ]
        public virtual ListViewItem EditItem {
            get {
                if (_editIndex > -1 && _editIndex < Items.Count) {
                    return Items[_editIndex];
                }
                return null;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewDataItem), BindingDirection.TwoWay),
        ResourceDescription("ListView_EditItemTemplate"),
        ]
        public virtual ITemplate EditItemTemplate {
            get {
                return _editItemTemplate;
            }
            set {
                _editItemTemplate = value;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListView)),
        ResourceDescription("ListView_EmptyDataTemplate"),
        ]
        public virtual ITemplate EmptyDataTemplate {
            get {
                return _emptyDataTemplate;
            }
            set {
                _emptyDataTemplate = value;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewItem)),
        ResourceDescription("ListView_EmptyItemTemplate"),
        ]
        public virtual ITemplate EmptyItemTemplate {
            get {
                return _emptyItemTemplate;
            }
            set {
                _emptyItemTemplate = value;
            }
        }

        [
        WebCategory("Behavior"),
        DefaultValue(true),
        ResourceDescription("ListView_EnableModelValidation")
        ]
        public virtual bool EnableModelValidation {
            get {
                object o = ViewState["EnableModelValidation"];
                if (o != null) {
                    return (bool)o;
                }
                return true;
            }
            set {
                ViewState["EnableModelValidation"] = value;
            }
        }

        [
        WebCategory("Behavior"),
        DefaultValue(false),
        ResourceDescription("ListView_EnablePersistedSelection")
        ]
        public virtual bool EnablePersistedSelection {
            get {
                object o = ViewState["EnablePersistedSelection"];
                if (o != null) {
                    return (bool)o;
                }
                return false;
            }
            set {
                ViewState["EnablePersistedSelection"] = value;
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override FontInfo Font {
            get {
                return base.Font;
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override Color ForeColor {
            get {
                return base.ForeColor;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        [
        DefaultValue("groupPlaceholder"),
        Category("Behavior"),
        ResourceDescription("ListView_GroupPlaceholderID"),
        SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")
        ]
        public virtual String GroupPlaceholderID {
            get {
                object o = ViewState["GroupPlaceholderID"];
                if (o != null) {
                    return (String)o;
                }
                return "groupPlaceholder";
            }
            set {
                if (String.IsNullOrEmpty(value)) {
                    throw new ArgumentOutOfRangeException("value", String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_ContainerNameMustNotBeEmpty, "GroupPlaceholderID"));
                }
                ViewState["GroupPlaceholderID"] = value;
            }
        }

        [
        Category("Default"),
        DefaultValue(1),
        ResourceDescription("ListView_GroupItemCount"),
        ]
        public virtual int GroupItemCount {
            get {
                return _groupItemCount;
            }
            set {
                if (value < 1) {
                    throw new ArgumentOutOfRangeException("value");
                }
                _groupItemCount = value;
                SetRequiresDataBindingIfInitialized();
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewItem)),
        ResourceDescription("ListView_GroupSeparatorTemplate"),
        ]
        public virtual ITemplate GroupSeparatorTemplate {
            get {
                return _groupSeparatorTemplate;
            }
            set {
                _groupSeparatorTemplate = value;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewItem)),
        ResourceDescription("ListView_GroupTemplate"),
        ]
        public virtual ITemplate GroupTemplate {
            get {
                return _groupTemplate;
            }
            set {
                _groupTemplate = value;
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override Unit Height {
            get {
                return base.Height;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResourceDescription("ListView_InsertItem")
        ]
        public virtual ListViewItem InsertItem {
            get {
                return _insertItem;
            }
        }

        [
        Category("Default"),
        DefaultValue(InsertItemPosition.None),
        ResourceDescription("ListView_InsertItemPosition")
        ]
        public virtual InsertItemPosition InsertItemPosition {
            get {
                object o = ViewState["InsertItemPosition"];
                if (o != null) {
                    return (InsertItemPosition)o;
                }
                return InsertItemPosition.None;
            }
            set {
                if (InsertItemPosition != value) {
                    ViewState["InsertItemPosition"] = value;
                    SetRequiresDataBindingIfInitialized();
                }
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewItem), BindingDirection.TwoWay),
        ResourceDescription("ListView_InsertItemTemplate"),
        ]
        public virtual ITemplate InsertItemTemplate {
            get {
                return _insertItemTemplate;
            }
            set {
                _insertItemTemplate = value;
            }
        }

        [
        DefaultValue("itemPlaceholder"),
        Category("Behavior"),
        ResourceDescription("ListView_ItemPlaceholderID"),
        SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")
        ]
        public virtual String ItemPlaceholderID {
            get {
                object o = ViewState["ItemPlaceholderID"];
                if (o != null) {
                    return (String)o;
                }
                return "itemPlaceholder";
            }
            set {
                if (String.IsNullOrEmpty(value)) {
                    throw new ArgumentOutOfRangeException("value", String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_ContainerNameMustNotBeEmpty, "ItemPlaceholderID"));
                }
                ViewState["ItemPlaceholderID"] = value;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResourceDescription("ListView_Items")
        ]
        public virtual IList<ListViewDataItem> Items {
            get {
                if (_itemList == null) {
                    _itemList = new List<ListViewDataItem>();
                }
                return _itemList;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewItem)),
        ResourceDescription("ListView_ItemSeparatorTemplate"),
        ]
        public virtual ITemplate ItemSeparatorTemplate {
            get {
                return _itemSeparatorTemplate;
            }
            set {
                _itemSeparatorTemplate = value;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewDataItem), BindingDirection.TwoWay),
        ResourceDescription("ListView_ItemTemplate"),
        SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
            Justification = "Interface denotes existence of property, not used for security.")
        ]
        public virtual ITemplate ItemTemplate {
            get {
                return _itemTemplate;
            }
            set {
                _itemTemplate = value;
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListView)),
        ResourceDescription("ListView_LayoutTemplate"),
        ]
        public virtual ITemplate LayoutTemplate {
            get {
                return _layoutTemplate;
            }
            set {
                _layoutTemplate = value;
            }
        }

        [
        DefaultValue(null),
        TypeConverterAttribute(typeof(StringArrayConverter)),
        WebCategory("Data"),
        ]
        public virtual string[] ClientIDRowSuffix {
            get {
                object o = _clientIDRowSuffix;
                if (o != null) {
                    return (string[])((string[])o).Clone();
                }
                return new string[0];
            }
            set {
                if (!DataBoundControlHelper.CompareStringArrays(value, ClientIDRowSuffixInternal)) {
                    if (value != null) {
                        _clientIDRowSuffix = (string[])value.Clone();
                    }
                    else {
                        _clientIDRowSuffix = null;
                    }
                    _clientIDRowSuffixArrayList = null;
                    if (Initialized) {
                        RequiresDataBinding = true;
                    }
                }
            }
        }

        private string[] ClientIDRowSuffixInternal {
            get {
                object o = _clientIDRowSuffix;
                if (o != null) {
                    return (string[])o;
                }
                return new string[0];
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public virtual DataKey SelectedDataKey {
            get {
                if (DataKeyNamesInternal == null || DataKeyNamesInternal.Length == 0) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_DataKeyNamesMustBeSpecified, ID));
                }

                DataKeyArray keys = DataKeys;
                int selectedIndex = SelectedIndex;
                if (keys != null && selectedIndex < keys.Count && selectedIndex > -1) {
                    return keys[selectedIndex];
                }
                return null;
            }
        }

        [
        Category("Default"),
        DefaultValue(-1),
        ResourceDescription("ListView_SelectedIndex"),
        SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
            Justification = "Interface denotes existence of property, not used for security.")
        ]
        public virtual int SelectedIndex {
            get {
                return _selectedIndex;
            }
            set {
                if (value < -1) {
                    throw new ArgumentOutOfRangeException("value");
                }
                if (value != _selectedIndex) {
                    // update the virtual selection to use the new selection
                    _selectedIndex = value;

                    if (EnablePersistedSelection && (DataKeyNamesInternal.Length > 0)) {
                        SelectedPersistedDataKey = SelectedDataKey;
                    }

                    // we're going to rebind here for a new template
                    SetRequiresDataBindingIfInitialized();
                }
            }
        }

        [
        Browsable(false),
        DefaultValue(null),
        PersistenceMode(PersistenceMode.InnerProperty),
        TemplateContainer(typeof(ListViewDataItem), BindingDirection.TwoWay),
        ResourceDescription("ListView_SelectedItemTemplate"),
        ]
        public virtual ITemplate SelectedItemTemplate {
            get {
                return _selectedItemTemplate;
            }
            set {
                _selectedItemTemplate = value;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public object SelectedValue {
            get {
                DataKey selectedDataKey = SelectedDataKey;
                if (selectedDataKey != null) {
                    return SelectedDataKey.Value;
                }
                return null;
            }
        }

        [
        Browsable(false),
        DefaultValue(SortDirection.Ascending),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        PersistenceMode(PersistenceMode.InnerProperty),
        ResourceDescription("ListView_SortDirection"),
        ResourceCategory("Sorting"),
        ]
        public virtual SortDirection SortDirection {
            get {
                return SortDirectionInternal;
            }
        }

        /// <summary>
        ///    Internal member for setting sort direction
        /// </summary>
        private SortDirection SortDirectionInternal {
            get {
                return _sortDirection;
            }
            set {
                if (value < SortDirection.Ascending || value > SortDirection.Descending) {
                    throw new ArgumentOutOfRangeException("value");
                }
                if (_sortDirection != value) {
                    _sortDirection = value;
                    SetRequiresDataBindingIfInitialized();
                }
            }
        }

        /// <summary>
        /// Gets a value that specifies the current column being sorted on in the
        /// <see cref='System.Web.UI.WebControls.GridView'/>.
        /// </summary>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResourceDescription("ListView_SortExpression"),
        ResourceCategory("Sorting"),
        ]
        public virtual string SortExpression {
            get {
                return SortExpressionInternal;
            }
        }

        /// <summary>
        ///    Internal member for setting sort expression
        /// </summary>
        private string SortExpressionInternal {
            get {
                return _sortExpression;
            }
            set {
                if (_sortExpression != value) {
                    _sortExpression = value;
                    SetRequiresDataBindingIfInitialized();
                }
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override short TabIndex {
            get {
                return base.TabIndex;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override string ToolTip {
            get {
                return base.ToolTip;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        [
        Browsable(false)
        ]
        public virtual DataKey SelectedPersistedDataKey {
            get {
                return _persistedDataKey;
            }
            set {
                _persistedDataKey = value;
                if (IsTrackingViewState && (_persistedDataKey != null)) {
                    ((IStateManager)_persistedDataKey).TrackViewState();
                }
            }
        }

        // Override style properties and throw from setter, and set Browsable(false).
        // Don't throw from getters because designer calls getters through reflection.
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public override Unit Width {
            get {
                return base.Width;
            }
            set {
                throw new NotSupportedException(AtlasWeb.ListView_StylePropertiesNotSupported);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='delete'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemDeleted")
        ]
        public event EventHandler<ListViewDeletedEventArgs> ItemDeleted {
            add {
                Events.AddHandler(EventItemDeleted, value);
            }
            remove {
                Events.RemoveHandler(EventItemDeleted, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='insert'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemInserted")
        ]
        public event EventHandler<ListViewInsertedEventArgs> ItemInserted {
            add {
                Events.AddHandler(EventItemInserted, value);
            }
            remove {
                Events.RemoveHandler(EventItemInserted, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='update'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemUpdated")
        ]
        public event EventHandler<ListViewUpdatedEventArgs> ItemUpdated {
            add {
                Events.AddHandler(EventItemUpdated, value);
            }
            remove {
                Events.RemoveHandler(EventItemUpdated, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='Command'/> property of
        /// <see langword='cancel'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemCanceling")
        ]
        public event EventHandler<ListViewCancelEventArgs> ItemCanceling {
            add {
                Events.AddHandler(EventItemCanceling, value);
            }
            remove {
                Events.RemoveHandler(EventItemCanceling, value);
            }
        }

        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> not covered by
        /// <see langword='edit'/>, <see langword='cancel'/>, <see langword='delete'/> or
        /// <see langword='update'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemCommand")
        ]
        public event EventHandler<ListViewCommandEventArgs> ItemCommand {
            add {
                Events.AddHandler(EventItemCommand, value);
            }
            remove {
                Events.RemoveHandler(EventItemCommand, value);
            }
        }

        /// <devdoc>
        ///    <para>Occurs on the server when a control a created.</para>
        /// </devdoc>
        [
        Category("Behavior"),
        ResourceDescription("ListView_OnItemCreated")
        ]
        public event EventHandler<ListViewItemEventArgs> ItemCreated {
            add {
                Events.AddHandler(EventItemCreated, value);
            }
            remove {
                Events.RemoveHandler(EventItemCreated, value);
            }
        }

        /// <devdoc>
        ///    <para>Occurs when an Item is data bound to the control.</para>
        /// </devdoc>
        [
        Category("Data"),
        ResourceDescription("ListView_OnItemDataBound")
        ]
        public event EventHandler<ListViewItemEventArgs> ItemDataBound {
            add {
                Events.AddHandler(EventItemDataBound, value);
            }
            remove {
                Events.RemoveHandler(EventItemDataBound, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='delete'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemDeleting")
        ]
        public event EventHandler<ListViewDeleteEventArgs> ItemDeleting {
            add {
                Events.AddHandler(EventItemDeleting, value);
            }
            remove {
                Events.RemoveHandler(EventItemDeleting, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='Command'/> property of
        /// <see langword='edit'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemEditing")
        ]
        public event EventHandler<ListViewEditEventArgs> ItemEditing {
            add {
                Events.AddHandler(EventItemEditing, value);
            }
            remove {
                Events.RemoveHandler(EventItemEditing, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='insert'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemInserting")
        ]
        public event EventHandler<ListViewInsertEventArgs> ItemInserting {
            add {
                Events.AddHandler(EventItemInserting, value);
            }
            remove {
                Events.RemoveHandler(EventItemInserting, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs when a control bubbles an event to the <see cref='System.Web.UI.WebControls.ListView'/> with a
        /// <see langword='update'/>.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnItemUpdating")
        ]
        public event EventHandler<ListViewUpdateEventArgs> ItemUpdating {
            add {
                Events.AddHandler(EventItemUpdating, value);
            }
            remove {
                Events.RemoveHandler(EventItemUpdating, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs on the server when a control layout is created.</para>
        /// </devdoc>
        [
        Category("Behavior"),
        ResourceDescription("ListView_OnLayoutCreated")
        ]
        public event EventHandler LayoutCreated {
            add {
                Events.AddHandler(EventLayoutCreated, value);
            }
            remove {
                Events.RemoveHandler(EventLayoutCreated, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs on the server when the page properties have changed.</para>
        /// </devdoc>
        [
        Category("Behavior"),
        ResourceDescription("ListView_OnPagePropertiesChanged")
        ]
        public event EventHandler PagePropertiesChanged {
            add {
                Events.AddHandler(EventPagePropertiesChanged, value);
            }
            remove {
                Events.RemoveHandler(EventPagePropertiesChanged, value);
            }
        }

        /// <devdoc>
        /// <para>Occurs on the server when the page properties are changing.</para>
        /// </devdoc>
        [
        Category("Behavior"),
        ResourceDescription("ListView_OnPagePropertiesChanging")
        ]
        public event EventHandler<PagePropertiesChangingEventArgs> PagePropertiesChanging {
            add {
                Events.AddHandler(EventPagePropertiesChanging, value);
            }
            remove {
                Events.RemoveHandler(EventPagePropertiesChanging, value);
            }
        }

        /// <devdoc>
        ///    <para>Occurs when an Item on the list is selected.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnSelectedIndexChanged")
        ]
        public event EventHandler SelectedIndexChanged {
            add {
                Events.AddHandler(EventSelectedIndexChanged, value);
            }
            remove {
                Events.RemoveHandler(EventSelectedIndexChanged, value);
            }
        }

        /// <devdoc>
        ///    <para>Occurs when an Item on the list is selected.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnSelectedIndexChanging")
        ]
        public event EventHandler<ListViewSelectEventArgs> SelectedIndexChanging {
            add {
                Events.AddHandler(EventSelectedIndexChanging, value);
            }
            remove {
                Events.RemoveHandler(EventSelectedIndexChanging, value);
            }
        }

        /// <devdoc>
        ///    <para>Occurs when a field is sorted.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnSorted")
        ]
        public event EventHandler Sorted {
            add {
                Events.AddHandler(EventSorted, value);
            }
            remove {
                Events.RemoveHandler(EventSorted, value);
            }
        }

        /// <devdoc>
        ///    <para>Occurs when a field is sorting.</para>
        /// </devdoc>
        [
        Category("Action"),
        ResourceDescription("ListView_OnSorting")
        ]
        public event EventHandler<ListViewSortEventArgs> Sorting {
            add {
                Events.AddHandler(EventSorting, value);
            }
            remove {
                Events.RemoveHandler(EventSorting, value);
            }
        }

        protected override bool IsUsingModelBinders {
            get {
                return !String.IsNullOrEmpty(SelectMethod) ||
                       !String.IsNullOrEmpty(UpdateMethod) ||
                       !String.IsNullOrEmpty(DeleteMethod) ||
                       !String.IsNullOrEmpty(InsertMethod);
            }
        }

        /// <summary>
        /// The name of the method on the page which is called when this Control does an update operation.
        /// </summary>
        [
        DefaultValue(""),
        Themeable(false),
        WebCategory("Data"),
        WebSysDescription(SR.DataBoundControl_UpdateMethod)
        ]
        public virtual string UpdateMethod {
            get {
                return _updateMethod ?? String.Empty;
            }
            set {
                if (!String.Equals(_updateMethod, value, StringComparison.OrdinalIgnoreCase)) {
                    _updateMethod = value;
                    OnDataPropertyChanged();
                }
            }
        }

        /// <summary>
        /// The name of the method on the page which is called when this Control does a delete operation.
        /// </summary>
        [
        DefaultValue(""),
        Themeable(false),
        WebCategory("Data"),
        WebSysDescription(SR.DataBoundControl_DeleteMethod)
        ]
        public virtual string DeleteMethod {
            get {
                return _deleteMethod ?? String.Empty;
            }
            set {
                if (!String.Equals(_deleteMethod, value, StringComparison.OrdinalIgnoreCase)) {
                    _deleteMethod = value;
                    OnDataPropertyChanged();
                }
            }
        }

        /// <summary>
        /// The name of the method on the page which is called when this Control does an insert operation.
        /// </summary>
        [
        DefaultValue(""),
        Themeable(false),
        WebCategory("Data"),
        WebSysDescription(SR.DataBoundControl_InsertMethod)
        ]
        public virtual string InsertMethod {
            get {
                return _insertMethod ?? String.Empty;
            }
            set {
                if (!String.Equals(_insertMethod, value, StringComparison.OrdinalIgnoreCase)) {
                    _insertMethod = value;
                    OnDataPropertyChanged();
                }
            }
        }

        protected virtual void AddControlToContainer(Control control, Control container, int addLocation) {
            // The ListView packages up everything in the ItemTemplate in a ListViewDataItem or ListViewItem.
            // The ListViewItem is being added to the control tree.  Since ListViewItems can't be children of HtmlTables or
            // HtmlTableRows, we put them in a derived HtmlTable or HtmlTableRow, which just renders out its children.
            // Since ListViewItems don't have any rendering, only the child HtmlTableRow or HtmlTableCell will be rendered.

            if (container is HtmlTable) {
                ListViewTableRow listViewTableRow = new ListViewTableRow();
                container.Controls.AddAt(addLocation, listViewTableRow);
                listViewTableRow.Controls.Add(control);
            }
            else {
                if (container is HtmlTableRow) {
                    ListViewTableCell listViewTableCell = new ListViewTableCell();
                    container.Controls.AddAt(addLocation, listViewTableCell);
                    listViewTableCell.Controls.Add(control);
                }
                else {
                    container.Controls.AddAt(addLocation, control);
                }
            }
        }

        private void AutoIDControl(Control control) {
            // We have to do our own auto-id'ing because we create the LayoutTemplate, add controls
            // to the item or group container, then clear those controls out when we bind again.
            // Because the item or group container isn't necessarily a naming container, clearing
            // out its controls collection doesn't reset the auto-id counter and you get new ids.
            // On postback, controls that have post data won't be found because their generated
            // ids won't match the prior ones.  By creating our own auto-id'ing, we don't get
            // Control's auto-id, and we can reset the auto id index when we remove all items from
            // the item or group container.
            control.ID = _automaticIDPrefix + _autoIDIndex++.ToString(CultureInfo.InvariantCulture);
        }

        private void ClearDataKeys() {
            _dataKeysArrayList = null;
        }

        /// <summary>
        /// Overriden by DataBoundControl to determine if the control should
        /// recreate its control hierarchy based on values in view state.
        /// If the control hierarchy should be created, i.e. view state does
        /// exist, it calls CreateChildControls with a dummy (empty) data source
        /// which is usable for enumeration purposes only.
        /// </summary>
        protected internal override void CreateChildControls() {
            object controlCount = ViewState[ItemCountViewStateKey];

            if (controlCount == null && RequiresDataBinding) {
                EnsureDataBound();
            }

            if (controlCount != null && ((int)controlCount) != -1) {
                object[] dummyDataSource = new object[(int)controlCount];
                CreateChildControls(dummyDataSource, false);
                ClearChildViewState();
            }
        }

        /// <summary>
        /// Performs the work of creating the control hierarchy based on a data source.
        /// When dataBinding is true, the specified data source contains real
        /// data, and the data is supposed to be pushed into the UI.
        /// When dataBinding is false, the specified data source is a dummy data
        /// source, that allows enumerating the right number of items, but the items
        /// themselves are null and do not contain data. In this case, the recreated
        /// control hierarchy reinitializes its state from view state.
        /// It enables a DataBoundControl to encapsulate the logic of creating its
        /// control hierarchy in both modes into a single code path.
        /// </summary>
        /// <param name="dataSource">
        /// The data source to be used to enumerate items.
        /// </param>
        /// <param name="dataBinding">
        /// Whether the method has been called from DataBind or not.
        /// </param>
        /// <returns>
        /// The number of items created based on the data source. Put another way, its
        /// the number of items enumerated from the data source.
        /// </returns>
        protected virtual int CreateChildControls(IEnumerable dataSource, bool dataBinding) {
            ListViewPagedDataSource pagedDataSource = null;

            // Create the LayoutTemplate so the pager control in it can set page properties.
            // We'll only create the layout template once.

            EnsureLayoutTemplate();
            RemoveItems();

            // if we should render the insert item, make a dummy empty datasource and go through
            // the regular code path.
            if (dataSource == null && InsertItemPosition != InsertItemPosition.None) {
                dataSource = new object[0];
            }

            bool usePaging = (_startRowIndex > 0 || _maximumRows > 0);

            if (dataBinding) {
                DataSourceView view = GetData();
                DataSourceSelectArguments arguments = SelectArguments;
                if (view == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NullView, ID));
                }

                bool useServerPaging = view.CanPage && usePaging;

                if (!view.CanPage && useServerPaging) {
                    if (dataSource != null && !(dataSource is ICollection)) {
                        arguments.StartRowIndex = _startRowIndex;
                        arguments.MaximumRows = _maximumRows;
                        // This should throw an exception saying the data source can't page.
                        // We do this because the data source can provide a better error message than we can.
                        view.Select(arguments, SelectCallback);
                    }
                }

                if (useServerPaging) {
                    int totalRowCount;
                    if (view.CanRetrieveTotalRowCount) {
                        totalRowCount = arguments.TotalRowCount;
                    }
                    else {
                        ICollection dataSourceCollection = dataSource as ICollection;
                        if (dataSourceCollection == null) {
                            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NeedICollectionOrTotalRowCount, GetType().Name));
                        }
                        totalRowCount = checked(_startRowIndex + dataSourceCollection.Count);
                    }
                    pagedDataSource = CreateServerPagedDataSource(totalRowCount);

                }
                else {
                    pagedDataSource = CreatePagedDataSource();
                }
            }
            else {
                pagedDataSource = CreatePagedDataSource();
            }

            ArrayList keyArray = DataKeysArrayList;
            ArrayList suffixArray = ClientIDRowSuffixArrayList;
            _dataKeyArray = null;
            _clientIDRowSuffixArray = null;

            ICollection collection = dataSource as ICollection;

            if (dataBinding) {
                keyArray.Clear();
                suffixArray.Clear();
                if ((dataSource != null) && (collection == null) && !pagedDataSource.IsServerPagingEnabled && usePaging) {
                    // If we got to here, it's because the data source view said it could page, but then returned
                    // something that wasn't an ICollection.  Probably a data source control author error.
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_Missing_VirtualItemCount, ID));
                }
            }
            else {
                if (collection == null) {
                    throw new InvalidOperationException(AtlasWeb.ListView_DataSourceMustBeCollectionWhenNotDataBinding);
                }
            }

            if (dataSource != null) {
                pagedDataSource.DataSource = dataSource;
                if (dataBinding && usePaging) {
                    keyArray.Capacity = pagedDataSource.DataSourceCount;
                    suffixArray.Capacity = pagedDataSource.DataSourceCount;
                }

                if (_groupTemplate != null) {
                    _itemList = CreateItemsInGroups(pagedDataSource, dataBinding, InsertItemPosition, keyArray);
                    if (dataBinding && ClientIDRowSuffixInternal != null && ClientIDRowSuffixInternal.Length != 0) {
                        CreateSuffixArrayList(pagedDataSource, suffixArray);
                    }
                }
                else {
                    if (GroupItemCount != 1) {
                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_GroupItemCountNoGroupTemplate, ID, GroupPlaceholderID));
                    }

                    _itemList = CreateItemsWithoutGroups(pagedDataSource, dataBinding, InsertItemPosition, keyArray);
                    if(dataBinding && ClientIDRowSuffixInternal != null && ClientIDRowSuffixInternal.Length != 0) {
                        CreateSuffixArrayList(pagedDataSource, suffixArray);
                    }
                }

                _totalRowCount = usePaging ? pagedDataSource.DataSourceCount : _itemList.Count;
                OnTotalRowCountAvailable(new PageEventArgs(_startRowIndex, _maximumRows, _totalRowCount));

                if (_itemList.Count == 0) {
                    if (InsertItemPosition == InsertItemPosition.None) {
                        // remove the layout template
                        Controls.Clear();
                        CreateEmptyDataItem();
                    }
                }
            }
            else {
                // remove the layout template
                Controls.Clear();
                CreateEmptyDataItem();
            }

            return _totalRowCount;
        }

        // Style properties won't be honored on ListView, so throw if someone tries to set any style properties
        protected override Style CreateControlStyle() {
            // The designer reflects on properties at design time.  Don't throw then.
            if (!DesignMode) {
                throw new NotSupportedException(AtlasWeb.ListView_StyleNotSupported);
            }
            return base.CreateControlStyle();
        }

        protected override DataSourceSelectArguments CreateDataSourceSelectArguments() {
            DataSourceSelectArguments arguments = new DataSourceSelectArguments();
            DataSourceView view = GetData();
            bool useServerPaging = view.CanPage;

            string sortExpression = SortExpressionInternal;
            if (SortDirectionInternal == SortDirection.Descending && !String.IsNullOrEmpty(sortExpression)) {
                sortExpression += " DESC";
            }
            arguments.SortExpression = sortExpression;

            // decide if we should use server-side paging
            if (useServerPaging) {
                if (view.CanRetrieveTotalRowCount) {
                    arguments.RetrieveTotalRowCount = true;
                    arguments.MaximumRows = _maximumRows;
                }
                else {
                    arguments.MaximumRows = -1;
                }
                arguments.StartRowIndex = _startRowIndex;
            }
            return arguments;
        }

        protected virtual void CreateEmptyDataItem() {
            if (_emptyDataTemplate != null) {
                _instantiatedEmptyDataTemplate = true;
                ListViewItem item = CreateItem(ListViewItemType.EmptyItem);
                AutoIDControl(item);
                InstantiateEmptyDataTemplate(item);
                OnItemCreated(new ListViewItemEventArgs(item));
                AddControlToContainer(item, this, 0);
            }
        }

        protected virtual ListViewItem CreateEmptyItem() {
            if (_emptyItemTemplate != null) {
                ListViewItem emptyItem = CreateItem(ListViewItemType.EmptyItem);
                AutoIDControl(emptyItem);
                InstantiateEmptyItemTemplate(emptyItem);
                OnItemCreated(new ListViewItemEventArgs(emptyItem));
                return emptyItem;
            }
            return null;
        }

        protected virtual ListViewItem CreateInsertItem() {
            if (InsertItemTemplate == null) {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_InsertTemplateRequired, ID));
            }

            ListViewItem item = CreateItem(ListViewItemType.InsertItem);
            AutoIDControl(item);
            InstantiateInsertItemTemplate(item);
            OnItemCreated(new ListViewItemEventArgs(item));
            return item;
        }

        protected virtual ListViewItem CreateItem(ListViewItemType itemType) {
            ListViewItem item = new ListViewItem(itemType);
            if (itemType == ListViewItemType.InsertItem) {
                _insertItem = item;
            }
            return item;
        }

        protected virtual ListViewDataItem CreateDataItem(int dataItemIndex, int displayIndex) {
            return new ListViewDataItem(dataItemIndex, displayIndex);
        }

        protected virtual IList<ListViewDataItem> CreateItemsWithoutGroups(ListViewPagedDataSource dataSource, bool dataBinding, InsertItemPosition insertPosition, ArrayList keyArray) {
            // If this is the first time we're creating the control items, we need
            // to locate the itemPlaceholder container.
            // If this is a scenario where we are recreating control items, we already
            // have the cached itemPlaceholder container.
            if (_noGroupsOriginalIndexOfItemPlaceholderInContainer == -1) {
                _noGroupsItemPlaceholderContainer = GetPreparedContainerInfo(this, true, out _noGroupsOriginalIndexOfItemPlaceholderInContainer);
            }

            // We need to keep track of where we're inserting items and how many items we have
            // inserted so that if we need to remove them we know what to do.
            int itemInsertLocation = _noGroupsOriginalIndexOfItemPlaceholderInContainer;

            List<ListViewDataItem> items = new List<ListViewDataItem>();
            int itemIndex = 0;
            int dataItemIndex = 0;

            if (insertPosition == InsertItemPosition.FirstItem) {
                ListViewItem insertItem = CreateInsertItem();
                AddControlToContainer(insertItem, _noGroupsItemPlaceholderContainer, itemInsertLocation);
                insertItem.DataBind();
                itemInsertLocation++;
                itemIndex++;
            }
            // Reset the selected index if we have a persisted datakey so we
            // can figure out what index to select based on the key
            ResetPersistedSelectedIndex();

            foreach (object o in dataSource) {
                if (itemIndex != 0 && _itemSeparatorTemplate != null) {
                    ListViewContainer itemSeparatorContainer = new ListViewContainer();
                    AutoIDControl(itemSeparatorContainer);
                    InstantiateItemSeparatorTemplate(itemSeparatorContainer);
                    AddControlToContainer(itemSeparatorContainer, _noGroupsItemPlaceholderContainer, itemInsertLocation);
                    itemInsertLocation++;
                }

                ListViewDataItem item = CreateDataItem(dataItemIndex + dataSource.StartRowIndex, dataItemIndex);
                AutoIDControl(item);

                if (dataBinding) {
                    item.DataItem = o;
                    OrderedDictionary keyTable = new OrderedDictionary(DataKeyNamesInternal.Length);
                    foreach (string keyName in DataKeyNamesInternal) {
                        object keyValue = DataBinder.GetPropertyValue(o, keyName);
                        keyTable.Add(keyName, keyValue);
                    }
                    if (keyArray.Count == dataItemIndex) {
                        keyArray.Add(new DataKey(keyTable, DataKeyNamesInternal));
                    }
                    else {
                        keyArray[dataItemIndex] = new DataKey(keyTable, DataKeyNamesInternal);
                    }
                }

                // If persisted selection is enabled and we have a data key then compare it to get the selected index
                if (EnablePersistedSelection) {
                    if (dataItemIndex < keyArray.Count) {
                        DataKey currentKey = (DataKey)keyArray[dataItemIndex];
                        SetPersistedDataKey(dataItemIndex, currentKey);
                    }
                }
                
                InstantiateItemTemplate(item, dataItemIndex);
                

                OnItemCreated(new ListViewItemEventArgs(item));
                AddControlToContainer(item, _noGroupsItemPlaceholderContainer, itemInsertLocation);
                itemInsertLocation++;
                items.Add(item);

                if (dataBinding) {
                    item.DataBind();
                    OnItemDataBound(new ListViewItemEventArgs(item));
                    item.DataItem = null;
                }

                dataItemIndex++;
                itemIndex++;
            }

            if (insertPosition == InsertItemPosition.LastItem) {
                if (_itemSeparatorTemplate != null) {
                    ListViewContainer itemSeparatorContainer = new ListViewContainer();
                    AutoIDControl(itemSeparatorContainer);
                    InstantiateItemSeparatorTemplate(itemSeparatorContainer);
                    AddControlToContainer(itemSeparatorContainer, _noGroupsItemPlaceholderContainer, itemInsertLocation);
                    itemInsertLocation++;
                }

                ListViewItem insertItem = CreateInsertItem();
                AddControlToContainer(insertItem, _noGroupsItemPlaceholderContainer, itemInsertLocation);
                insertItem.DataBind();
                itemInsertLocation++;
                itemIndex++;
            }

            _noGroupsItemCreatedCount = itemInsertLocation - _noGroupsOriginalIndexOfItemPlaceholderInContainer;

            return items;
        }

        private void ResetPersistedSelectedIndex() {
            // If there is already a persisted DataKey then we should reset
            // the selected index so that we pick a selected index base on 
            // a row that matches the DataKey if any
            if (EnablePersistedSelection && (_persistedDataKey != null)) {
                _selectedIndex = -1;
            }
        }

        private void SetPersistedDataKey(int dataItemIndex, DataKey currentKey) {
            if (_persistedDataKey == null) {
                // If there is no persisted DataKey then set it to the DataKey at the
                // the selected index
                if (_selectedIndex == dataItemIndex) {
                    _persistedDataKey = currentKey;
                }
            }
            else if (_persistedDataKey.Equals(currentKey)) {
                // Persist the selection by picking the selected index where DataKeys match
                _selectedIndex = dataItemIndex;
            }
        }

        protected virtual IList<ListViewDataItem> CreateItemsInGroups(ListViewPagedDataSource dataSource, bool dataBinding, InsertItemPosition insertPosition, ArrayList keyArray) {
            // If this is the first time we're creating the control items, we need
            // to locate the groupPlaceholder container.
            // If this is a scenario where we are recreating control items, we already
            // have the cached groupPlaceholder container.
            if (_groupsOriginalIndexOfGroupPlaceholderInContainer == -1) {
                _groupsGroupPlaceholderContainer = GetPreparedContainerInfo(this, false, out _groupsOriginalIndexOfGroupPlaceholderInContainer);
            }

            int groupInsertLocation = _groupsOriginalIndexOfGroupPlaceholderInContainer;
            _groupsItemCreatedCount = 0;

            int itemInsertLocation = 0;
            Control itemPlaceholderContainer = null;

            // Reset the selected index if we have a persisted datakey so we
            // can figure out what index to select based on the key
            ResetPersistedSelectedIndex();

            List<ListViewDataItem> items = new List<ListViewDataItem>();
            int itemIndex = 0;
            int dataItemIndex = 0;

            if (insertPosition == InsertItemPosition.FirstItem) {
                ListViewContainer groupContainer = new ListViewContainer();
                AutoIDControl(groupContainer);
                InstantiateGroupTemplate(groupContainer);
                AddControlToContainer(groupContainer, _groupsGroupPlaceholderContainer, groupInsertLocation);
                groupInsertLocation++;

                itemPlaceholderContainer = GetPreparedContainerInfo(groupContainer, true, out itemInsertLocation);

                ListViewItem insertItem = CreateInsertItem();
                AddControlToContainer(insertItem, itemPlaceholderContainer, itemInsertLocation);
                insertItem.DataBind();
                itemInsertLocation++;
                itemIndex++;
            }

            foreach (object o in dataSource) {
                if (itemIndex % _groupItemCount == 0) {
                    if (itemIndex != 0 && _groupSeparatorTemplate != null) {
                        ListViewContainer groupSeparatorContainer = new ListViewContainer();
                        AutoIDControl(groupSeparatorContainer);
                        InstantiateGroupSeparatorTemplate(groupSeparatorContainer);
                        AddControlToContainer(groupSeparatorContainer, _groupsGroupPlaceholderContainer, groupInsertLocation);
                        groupInsertLocation++;
                    }
                    ListViewContainer groupContainer = new ListViewContainer();
                    AutoIDControl(groupContainer);
                    InstantiateGroupTemplate(groupContainer);
                    AddControlToContainer(groupContainer, _groupsGroupPlaceholderContainer, groupInsertLocation);
                    groupInsertLocation++;

                    itemPlaceholderContainer = GetPreparedContainerInfo(groupContainer, true, out itemInsertLocation);
                }

                ListViewDataItem item = CreateDataItem(dataItemIndex + StartRowIndex, dataItemIndex);

                if (dataBinding) {
                    item.DataItem = o;
                    OrderedDictionary keyTable = new OrderedDictionary(DataKeyNamesInternal.Length);
                    foreach (string keyName in DataKeyNamesInternal) {
                        object keyValue = DataBinder.GetPropertyValue(o, keyName);
                        keyTable.Add(keyName, keyValue);
                    }
                    if (keyArray.Count == dataItemIndex) {
                        keyArray.Add(new DataKey(keyTable, DataKeyNamesInternal));
                    }
                    else {
                        keyArray[dataItemIndex] = new DataKey(keyTable, DataKeyNamesInternal);
                    }
                }
                // If persisted selection is enabled and we have a data key then compare it to get the selected index
                if (EnablePersistedSelection) {
                    if (dataItemIndex < keyArray.Count) {
                        DataKey currentKey = (DataKey)keyArray[dataItemIndex];
                        SetPersistedDataKey(dataItemIndex, currentKey);
                    }
                }

                InstantiateItemTemplate(item, dataItemIndex);

                OnItemCreated(new ListViewItemEventArgs(item));

                if (itemIndex % _groupItemCount != 0 && _itemSeparatorTemplate != null) {
                    ListViewContainer itemSeparatorContainer = new ListViewContainer();
                    InstantiateItemSeparatorTemplate(itemSeparatorContainer);
                    AddControlToContainer(itemSeparatorContainer, itemPlaceholderContainer, itemInsertLocation);
                    itemInsertLocation++;
                }


                AddControlToContainer(item, itemPlaceholderContainer, itemInsertLocation);
                itemInsertLocation++;
                items.Add(item);

                if (dataBinding) {
                    item.DataBind();
                    OnItemDataBound(new ListViewItemEventArgs(item));
                    item.DataItem = null;
                }

                itemIndex++;
                dataItemIndex++;
            }

            if (insertPosition == InsertItemPosition.LastItem) {
                if (itemIndex % _groupItemCount == 0) {
                    // start a new group
                    if (itemIndex != 0 && _groupSeparatorTemplate != null) {
                        ListViewContainer groupSeparatorContainer = new ListViewContainer();
                        AutoIDControl(groupSeparatorContainer);
                        InstantiateGroupSeparatorTemplate(groupSeparatorContainer);
                        AddControlToContainer(groupSeparatorContainer, _groupsGroupPlaceholderContainer, groupInsertLocation);
                        groupInsertLocation++;
                    }
                    ListViewContainer groupContainer = new ListViewContainer();
                    AutoIDControl(groupContainer);
                    InstantiateGroupTemplate(groupContainer);
                    AddControlToContainer(groupContainer, _groupsGroupPlaceholderContainer, groupInsertLocation);
                    groupInsertLocation++;

                    itemPlaceholderContainer = GetPreparedContainerInfo(groupContainer, true, out itemInsertLocation);
                }

                // use the existing group
                if (itemIndex % _groupItemCount != 0 && _itemSeparatorTemplate != null) {
                    ListViewContainer itemSeparatorContainer = new ListViewContainer();
                    InstantiateItemSeparatorTemplate(itemSeparatorContainer);
                    AddControlToContainer(itemSeparatorContainer, itemPlaceholderContainer, itemInsertLocation);
                    itemInsertLocation++;
                }

                ListViewItem insertItem = CreateInsertItem();
                AddControlToContainer(insertItem, itemPlaceholderContainer, itemInsertLocation);
                insertItem.DataBind();
                itemInsertLocation++;
                itemIndex++;
            }

            // fill in the rest of the items if there's an emptyItemTemplate
            if (_emptyItemTemplate != null) {
                while (itemIndex % _groupItemCount != 0) {
                    if (_itemSeparatorTemplate != null) {
                        ListViewContainer itemSeparatorContainer = new ListViewContainer();
                        InstantiateItemSeparatorTemplate(itemSeparatorContainer);
                        AddControlToContainer(itemSeparatorContainer, itemPlaceholderContainer, itemInsertLocation);
                        itemInsertLocation++;
                    }

                    ListViewItem emptyItem = CreateEmptyItem();
                    AddControlToContainer(emptyItem, itemPlaceholderContainer, itemInsertLocation);
                    itemInsertLocation++;
                    itemIndex++;
                }
            }

            _groupsItemCreatedCount = groupInsertLocation - _groupsOriginalIndexOfGroupPlaceholderInContainer;

            return items;
        }

        protected virtual void CreateSuffixArrayList(ListViewPagedDataSource dataSource, ArrayList suffixArray) {
            int dataItemIndex = 0;
            foreach (object o in dataSource) {
                OrderedDictionary suffixTable = new OrderedDictionary(ClientIDRowSuffixInternal.Length);
                foreach (string suffixName in ClientIDRowSuffixInternal) {
                    object suffixValue = DataBinder.GetPropertyValue(o, suffixName);
                    suffixTable.Add(suffixName, suffixValue);
                }
                if (suffixArray.Count == dataItemIndex) {
                    suffixArray.Add(new DataKey(suffixTable, ClientIDRowSuffixInternal));
                }
                else {
                    suffixArray[dataItemIndex] = new DataKey(suffixTable, ClientIDRowSuffixInternal);
                }
                dataItemIndex++;
            }
        }


        protected virtual void CreateLayoutTemplate() {
            // Reset data concerning where things are in the layout template since we're about to recreate it
            _noGroupsOriginalIndexOfItemPlaceholderInContainer = -1;
            _noGroupsItemCreatedCount = 0;
            _noGroupsItemPlaceholderContainer = null;

            _groupsOriginalIndexOfGroupPlaceholderInContainer = -1;
            _groupsItemCreatedCount = 0;
            _groupsGroupPlaceholderContainer = null;

            Control containerControl = new Control();
            if (_layoutTemplate != null) {
                _layoutTemplate.InstantiateIn(containerControl);
                Controls.Add(containerControl);
            }
            OnLayoutCreated(new EventArgs());
        }

        private ListViewPagedDataSource CreatePagedDataSource() {
            ListViewPagedDataSource pagedDataSource = new ListViewPagedDataSource();

            pagedDataSource.StartRowIndex = _startRowIndex;
            pagedDataSource.MaximumRows = _maximumRows;
            pagedDataSource.AllowServerPaging = false;
            pagedDataSource.TotalRowCount = 0;

            return pagedDataSource;
        }

        private ListViewPagedDataSource CreateServerPagedDataSource(int totalRowCount) {
            ListViewPagedDataSource pagedDataSource = new ListViewPagedDataSource();

            pagedDataSource.StartRowIndex = _startRowIndex;
            pagedDataSource.MaximumRows = _maximumRows;
            pagedDataSource.AllowServerPaging = true;
            pagedDataSource.TotalRowCount = totalRowCount;

            return pagedDataSource;
        }

        public virtual void DeleteItem(int itemIndex) {
            // use EnableModelVadliation as the causesValdiation param because the hosting page should not
            // be validated unless model validation is going to be used
            ResetModelValidationGroup(EnableModelValidation, String.Empty);
            HandleDelete(null, itemIndex);
        }

        protected virtual void EnsureLayoutTemplate() {
            if (this.Controls.Count == 0 || _instantiatedEmptyDataTemplate) {
                Controls.Clear();
                CreateLayoutTemplate();
            }
        }

        public virtual void ExtractItemValues(IOrderedDictionary itemValues, ListViewItem item, bool includePrimaryKey) {
            if (itemValues == null) {
                throw new ArgumentNullException("itemValues");
            }

            DataBoundControlHelper.ExtractValuesFromBindableControls(itemValues, item);

            IBindableTemplate bindableTemplate = null;
            if (item.ItemType == ListViewItemType.DataItem) {
                ListViewDataItem dataItem = item as ListViewDataItem;
                if (dataItem == null) {
                    throw new InvalidOperationException(AtlasWeb.ListView_ItemsNotDataItems);
                }

                if (dataItem.DisplayIndex == EditIndex) {
                    bindableTemplate = EditItemTemplate as IBindableTemplate;
                }
                else if (dataItem.DisplayIndex == SelectedIndex) {
                    bindableTemplate = SelectedItemTemplate as IBindableTemplate;
                }
                else if (dataItem.DisplayIndex % 2 == 1 && AlternatingItemTemplate != null) {
                    bindableTemplate = AlternatingItemTemplate as IBindableTemplate;
                }
                else {
                    bindableTemplate = ItemTemplate as IBindableTemplate;
                }
            }
            else if (item.ItemType == ListViewItemType.InsertItem) {
                if (InsertItemTemplate != null) {
                    bindableTemplate = InsertItemTemplate as IBindableTemplate;
                }
            }

            if (bindableTemplate != null) {
                OrderedDictionary newValues = new OrderedDictionary();

                bool convertEmptyStringToNull = ConvertEmptyStringToNull;
                foreach (DictionaryEntry entry in bindableTemplate.ExtractValues(item)) {
                    object value = entry.Value;
                    if (convertEmptyStringToNull && value is string && ((string)value).Length == 0) {
                        newValues[entry.Key] = null;
                    }
                    else {
                        newValues[entry.Key] = value;
                    }
                }

                foreach (DictionaryEntry entry in newValues) {
                    if (includePrimaryKey || (Array.IndexOf(DataKeyNamesInternal, entry.Key) == -1)) {
                        itemValues[entry.Key] = entry.Value;
                    }
                }
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")]
        protected virtual Control FindPlaceholder(string containerID, Control container) {
            return container.FindControl(containerID);
        }

        private DataPager FindDataPager(Control control) {
            foreach (Control c in control.Controls) {
                DataPager pager = c as DataPager;
                if (pager != null) {
                    return pager;
                }
            }

            foreach (Control c in control.Controls) {
                if (c is IPageableItemContainer) {
                    // Exit out if we've ventured into another ListView or pageable container, since that is the likely
                    // target of any embedded pagers.
                    return null;
                }

                DataPager pager = FindDataPager(c);
                if (pager != null) {
                    return pager;
                }
            }
            return null;
        }

        private int GetItemIndex(ListViewItem item, string commandArgument) {
            if (item != null) {
                ListViewDataItem dataItem = item as ListViewDataItem;
                if (dataItem != null) {
                    return dataItem.DisplayIndex;
                }
                return -1;
            }
            return Convert.ToInt32(commandArgument, CultureInfo.InvariantCulture);
        }

        private bool TryGetItemIndex(ListViewItem item, string commandArgument, out int itemIndex) {
            if (item != null) {
                ListViewDataItem dataItem = item as ListViewDataItem;
                itemIndex = (dataItem != null) ? dataItem.DisplayIndex : -1;
                // HandleCommand will throw detailed exception when item is not data item
                return true;
            }
            return Int32.TryParse(commandArgument, NumberStyles.Integer, CultureInfo.InvariantCulture, out itemIndex);
        }

        private Control GetPreparedContainerInfo(Control outerContainer, bool isItem, out int placeholderIndex) {
            // This function locates the ItemPlaceholder for a given container and prepares
            // it for child controls. Strategy:            
            // - Locate ItemPlaceholder 
            // - If it's not found and the user defined a layout template throw
            // - If it's not found and the user didn't define a layout/group template, add a default placeholder with the placeholder ID
            // - Store the placeholder's container and the placeholder's location in the container
            // - Remove the ItemPlaceholder

            string placeholderID = isItem ? ItemPlaceholderID : GroupPlaceholderID;
            Control placeholder = FindPlaceholder(placeholderID, outerContainer);
            if (placeholder == null) {
                //add a default placeholder
                if (_layoutTemplate == null) {
                    placeholder = new PlaceHolder();
                    placeholder.ID = placeholderID;
                }

                if (isItem) {
                    //throw if the user defined a layout/group template and didn't specify an item placeholder
                    if ((_layoutTemplate != null) || (_groupTemplate != null)) {
                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NoItemPlaceholder, ID, ItemPlaceholderID));
                    }
                }
                else {
                    //throw if the user defined a layout template and didn't specify an group placeholder
                    if (_layoutTemplate != null) {
                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NoGroupPlaceholder, ID, GroupPlaceholderID));
                    }
                }

                Controls.Add(placeholder);
            }

            // Save the information about where we found the itemPlaceholder because
            // in RemoveItems() we need to know where to delete whatever we create.
            // This only applies to certain usages of this function.
            Control placeholderContainer = placeholder.Parent;
            placeholderIndex = placeholderContainer.Controls.IndexOf(placeholder);

            // Remove the item placeholder since we're going to be
            // adding real items starting at the index where it used to be.
            placeholderContainer.Controls.Remove(placeholder);

            return placeholderContainer;
        }

        private void HandleCancel(int itemIndex) {
            ListViewCancelMode cancelMode = ListViewCancelMode.CancelingInsert;
            if (itemIndex == EditIndex && itemIndex >= 0) {
                cancelMode = ListViewCancelMode.CancelingEdit;
            }
            else if (itemIndex != -1) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidCancel);
            }

            ListViewCancelEventArgs e = new ListViewCancelEventArgs(itemIndex, cancelMode);
            OnItemCanceling(e);

            if (e.Cancel) {
                return;
            }

            if (IsDataBindingAutomatic) {
                if (e.CancelMode == ListViewCancelMode.CancelingEdit) {
                    EditIndex = -1;
                }
                else {
                    // cancel on an insert is simply "redatabind to clear"?
                }
            }

            RequiresDataBinding = true;
        }

        private void HandleDelete(ListViewItem item, int itemIndex) {
            ListViewDataItem dataItem = item as ListViewDataItem;
            if (itemIndex < 0 && dataItem == null) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidDelete);
            }

            DataSourceView view = null;
            bool isBoundToDataSourceControl = IsDataBindingAutomatic;

            if (isBoundToDataSourceControl) {
                view = GetData();
                if (view == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NullView, ID));
                }
            }

            if (item == null && itemIndex < Items.Count) {
                item = Items[itemIndex];
            }

            ListViewDeleteEventArgs e = new ListViewDeleteEventArgs(itemIndex);


            if (item != null) {
                ExtractItemValues(e.Values, item, false/*includePrimaryKey*/);
            }
            if (DataKeys.Count > itemIndex) {
                foreach (DictionaryEntry entry in DataKeys[itemIndex].Values) {
                    e.Keys.Add(entry.Key, entry.Value);
                    if (e.Values.Contains(entry.Key)) {
                        e.Values.Remove(entry.Key);
                    }
                }
            }
            

            OnItemDeleting(e);

            if (e.Cancel) {
                return;
            }

            _deletedItemIndex = itemIndex;

            if (isBoundToDataSourceControl) {
                _deleteKeys = e.Keys;
                _deleteValues = e.Values;

                view.Delete(e.Keys, e.Values, HandleDeleteCallback);
            }
        }

        private bool HandleDeleteCallback(int affectedRows, Exception ex) {
            ListViewDeletedEventArgs e = new ListViewDeletedEventArgs(affectedRows, ex);
            e.SetKeys(_deleteKeys);
            e.SetValues(_deleteValues);

            OnItemDeleted(e);
            _deleteKeys = null;
            _deleteValues = null;

            if (ex != null && !e.ExceptionHandled) {
                // If there is no validator in the validation group that could make sense
                // of the error, return false to proceed with standard exception handling.
                // But if there is one, we want to let it display its error instead of throwing.
                if (PageIsValidAfterModelException()) {
                    return false;
                }
            }
            EditIndex = -1;

            if (affectedRows > 0) {
                // Patch up the selected index if we deleted the last item on the last page.
                if ((_totalRowCount > 0) &&
                    (_deletedItemIndex == SelectedIndex) &&
                    (_deletedItemIndex + _startRowIndex == _totalRowCount)) {
                    SelectedIndex--;
                }
            }
            _deletedItemIndex = -1;

            RequiresDataBinding = true;
            return true;
        }

        private void HandleEdit(int itemIndex) {
            if (itemIndex < 0) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidEdit);
            }

            ListViewEditEventArgs e = new ListViewEditEventArgs(itemIndex);
            OnItemEditing(e);

            if (e.Cancel) {
                return;
            }

            EditIndex = e.NewEditIndex;

            RequiresDataBinding = true;
        }

        private bool HandleEvent(EventArgs e, bool causesValidation, string validationGroup) {
            bool handled = false;

            ResetModelValidationGroup(causesValidation, validationGroup);

            ListViewCommandEventArgs dce = e as ListViewCommandEventArgs;

            if (dce != null) {

                OnItemCommand(dce);
                if (dce.Handled) {
                    return true;
                }
                handled = true;

                string command = dce.CommandName;

                if (String.Equals(command, DataControlCommands.SelectCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleSelect(GetItemIndex(dce.Item, (string)dce.CommandArgument));
                }
                else if (String.Equals(command, DataControlCommands.SortCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleSort((string)dce.CommandArgument);
                }
                else if (String.Equals(command, DataControlCommands.EditCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleEdit(GetItemIndex(dce.Item, (string)dce.CommandArgument));
                }
                else if (String.Equals(command, DataControlCommands.CancelCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleCancel(GetItemIndex(dce.Item, (string)dce.CommandArgument));
                }
                else if (String.Equals(command, DataControlCommands.UpdateCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleUpdate(dce.Item, GetItemIndex(dce.Item, (string)dce.CommandArgument), causesValidation);
                }
                else if (String.Equals(command, DataControlCommands.DeleteCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleDelete(dce.Item, GetItemIndex(dce.Item, (string)dce.CommandArgument));
                }
                else if (String.Equals(command, DataControlCommands.InsertCommandName, StringComparison.OrdinalIgnoreCase)) {
                    HandleInsert(dce.Item, causesValidation);
                }
                else {
                    int itemIndex;
                    if (TryGetItemIndex(dce.Item, (string)dce.CommandArgument, out itemIndex)) {
                        handled = HandleCommand(dce.Item, itemIndex, command);
                    }
                }
            }

            return handled;
        }

        private bool HandleCommand(ListViewItem item, int itemIndex, string commandName) {
            DataSourceView view = null;

            if (IsDataBindingAutomatic) {
                view = GetData();
                if (view == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NullView, ID));
                }
            }
            else {
                return false;
            }

            if (!view.CanExecute(commandName)) {
                return false;
            }

            ListViewDataItem dataItem = item as ListViewDataItem;
            if (itemIndex < 0 && dataItem == null) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidCommand);
            }

            OrderedDictionary values = new OrderedDictionary();
            OrderedDictionary keys = new OrderedDictionary();
            if (item != null) {
                ExtractItemValues(values, item, false /*includePrimaryKey*/);
            }

            if (DataKeys.Count > itemIndex) {
                foreach (DictionaryEntry entry in DataKeys[itemIndex].Values) {
                    keys.Add(entry.Key, entry.Value);
                    if (values.Contains(entry.Key)) {
                        values.Remove(entry.Key);
                    }
                }
            }
            
            view.ExecuteCommand(commandName, keys, values, HandleCommandCallback);
            return true;
        }

        private bool HandleCommandCallback(int affectedRows, Exception ex) {
            if (ex != null) {
                // If there is no validator in the validation group that could make sense
                // of the error, return false to proceed with standard exception handling.
                // But if there is one, we want to let it display its error instead of throwing.
                if (PageIsValidAfterModelException()) {
                    return false;
                }
            }
            EditIndex = -1;

            RequiresDataBinding = true;
            return true;
        }

        private void HandleInsert(ListViewItem item, bool causesValidation) {
            if (item != null && item.ItemType != ListViewItemType.InsertItem) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidInsert);
            }

            if (causesValidation && Page != null && !Page.IsValid) {
                return;
            }

            if (item == null) {
                item = _insertItem;
            }
            if (item == null) {
                throw new InvalidOperationException(AtlasWeb.ListView_NoInsertItem);
            }

            DataSourceView view = null;
            bool isBoundToDataSourceControl = IsDataBindingAutomatic;

            if (isBoundToDataSourceControl) {
                view = GetData();
                if (view == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NullView, ID));
                }
            }

            ListViewInsertEventArgs e = new ListViewInsertEventArgs(item);


            ExtractItemValues(e.Values, item, true/*includeKeys*/);
            

            OnItemInserting(e);

            if (e.Cancel) {
                return;
            }

            if (isBoundToDataSourceControl) {
                _insertValues = e.Values;
                view.Insert(e.Values, HandleInsertCallback);
            }
        }

        private bool HandleInsertCallback(int affectedRows, Exception ex) {
            ListViewInsertedEventArgs e = new ListViewInsertedEventArgs(affectedRows, ex);
            e.SetValues(_insertValues);

            OnItemInserted(e);

            _insertValues = null;
            if (ex != null && !e.ExceptionHandled) {
                // If there is no validator in the validation group that could make sense
                // of the error, return false to proceed with standard exception handling.
                // But if there is one, we want to let it display its error instead of throwing.
                if (PageIsValidAfterModelException()) {
                    return false;
                }
                e.KeepInInsertMode = true;
            }

            if (IsUsingModelBinders && !Page.ModelState.IsValid) {
                e.KeepInInsertMode = true;
            }

            if (!e.KeepInInsertMode) {
                RequiresDataBinding = true;
            }
            return true;
        }

        private void HandleSelect(int itemIndex) {
            if (itemIndex < 0) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidSelect);
            }

            ListViewSelectEventArgs e = new ListViewSelectEventArgs(itemIndex);
            OnSelectedIndexChanging(e);

            if (e.Cancel) {
                return;
            }

            SelectedIndex = e.NewSelectedIndex;

            OnSelectedIndexChanged(EventArgs.Empty);
            RequiresDataBinding = true;
        }

        private void HandleSort(string sortExpression) {
            SortDirection futureSortDirection = SortDirection.Ascending;

            if ((SortExpressionInternal == sortExpression) && (SortDirectionInternal == SortDirection.Ascending)) {
                // switch direction
                futureSortDirection = SortDirection.Descending;
            }
            HandleSort(sortExpression, futureSortDirection);
        }

        private void HandleSort(string sortExpression, SortDirection sortDirection) {
            ListViewSortEventArgs e = new ListViewSortEventArgs(sortExpression, sortDirection);
            OnSorting(e);

            if (e.Cancel) {
                return;
            }

            if (IsDataBindingAutomatic) {
                ClearDataKeys();
                DataSourceView view = GetData();
                if (view == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NullView, ID));
                }

                EditIndex = -1;

                SortExpressionInternal = e.SortExpression;
                SortDirectionInternal = e.SortDirection;
                _startRowIndex = 0;
            }

            OnSorted(EventArgs.Empty);
            RequiresDataBinding = true;
        }

        private void HandleUpdate(ListViewItem item, int itemIndex, bool causesValidation) {
            ListViewDataItem dataItem = item as ListViewDataItem;
            if (itemIndex < 0 && dataItem == null) {
                throw new InvalidOperationException(AtlasWeb.ListView_InvalidUpdate);
            }

            if (causesValidation && Page != null && !Page.IsValid) {
                return;
            }

            DataSourceView view = null;
            bool isBoundToDataSourceControl = IsDataBindingAutomatic;

            if (isBoundToDataSourceControl) {
                view = GetData();
                if (view == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_NullView, ID));
                }
            }

            ListViewUpdateEventArgs e = new ListViewUpdateEventArgs(itemIndex);


            foreach (DictionaryEntry entry in BoundFieldValues) {
                e.OldValues.Add(entry.Key, entry.Value);
            }

            if (DataKeys.Count > itemIndex) {
                foreach (DictionaryEntry entry in DataKeys[itemIndex].Values) {
                    e.Keys.Add(entry.Key, entry.Value);
                }
            }

            if (dataItem == null && Items.Count > itemIndex) {
                dataItem = Items[itemIndex];
            }

            if (dataItem != null) {
                ExtractItemValues(e.NewValues, dataItem, true/*includePrimaryKey*/);
            }
            

            OnItemUpdating(e);

            if (e.Cancel) {
                return;
            }

            if (isBoundToDataSourceControl) {
                _updateKeys = e.Keys;
                _updateOldValues = e.OldValues;
                _updateNewValues = e.NewValues;

                view.Update(e.Keys, e.NewValues, e.OldValues, HandleUpdateCallback);
            }
        }

        private bool HandleUpdateCallback(int affectedRows, Exception ex) {
            ListViewUpdatedEventArgs e = new ListViewUpdatedEventArgs(affectedRows, ex);
            e.SetKeys(_updateKeys);
            e.SetOldValues(_updateOldValues);
            e.SetNewValues(_updateNewValues);

            OnItemUpdated(e);
            _updateKeys = null;
            _updateOldValues = null;
            _updateNewValues = null;
            if (ex != null && !e.ExceptionHandled) {
                // If there is no validator in the validation group that could make sense
                // of the error, return false to proceed with standard exception handling.
                // But if there is one, we want to let it display its error instead of throwing.
                if (PageIsValidAfterModelException()) {
                    return false;
                }
                e.KeepInEditMode = true;
            }

            if (IsUsingModelBinders && !Page.ModelState.IsValid) {
                e.KeepInEditMode = true;
            }

            // We need to databind here event if no records were affected because
            // changing the EditIndex required a rebind.  The event args give the programmer
            // the chance to cancel the bind so the edits aren't lost.
            if (!e.KeepInEditMode) {
                EditIndex = -1;
                RequiresDataBinding = true;
            }
            return true;
        }

        public virtual void InsertNewItem(bool causesValidation) {
            ResetModelValidationGroup(causesValidation, String.Empty);
            HandleInsert(null, causesValidation);
        }

        protected virtual void InstantiateEmptyDataTemplate(Control container) {
            if (_emptyDataTemplate != null) {
                _emptyDataTemplate.InstantiateIn(container);
            }
        }

        protected virtual void InstantiateEmptyItemTemplate(Control container) {
            if (_emptyItemTemplate != null) {
                _emptyItemTemplate.InstantiateIn(container);
            }
        }

        protected virtual void InstantiateGroupTemplate(Control container) {
            if (_groupTemplate != null) {
                _groupTemplate.InstantiateIn(container);
            }
        }

        protected virtual void InstantiateGroupSeparatorTemplate(Control container) {
            if (_groupSeparatorTemplate != null) {
                _groupSeparatorTemplate.InstantiateIn(container);
            }
        }

        protected virtual void InstantiateInsertItemTemplate(Control container) {
            if (_insertItemTemplate != null) {
                _insertItemTemplate.InstantiateIn(container);
            }
        }

        protected virtual void InstantiateItemSeparatorTemplate(Control container) {
            if (_itemSeparatorTemplate != null) {
                _itemSeparatorTemplate.InstantiateIn(container);
            }
        }

        protected virtual void InstantiateItemTemplate(Control container, int displayIndex) {
            ITemplate contentTemplate = _itemTemplate;

            if (contentTemplate == null) {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_ItemTemplateRequired, ID));
            }

            if (displayIndex % 2 == 1 && _alternatingItemTemplate != null) {
                contentTemplate = _alternatingItemTemplate;
            }
            if (displayIndex == _selectedIndex && _selectedItemTemplate != null) {
                contentTemplate = _selectedItemTemplate;
            }
            if (displayIndex == _editIndex && _editItemTemplate != null) {
                contentTemplate = _editItemTemplate;
            }

            contentTemplate.InstantiateIn(container);
        }

        protected internal override void LoadControlState(object savedState) {
            // Any properties that could have been set in the persistance need to be
            // restored to their defaults if they're not in ControlState, or they will
            // be restored to their persisted state instead of their empty state.
            _startRowIndex = 0;
            _maximumRows = -1;
            _editIndex = -1;
            _selectedIndex = -1;
            _groupItemCount = 1;
            _sortExpression = String.Empty;
            _sortDirection = SortDirection.Ascending;
            _dataKeyNames = new string[0];
            object[] state = savedState as object[];

            if (state != null) {
                base.LoadControlState(state[0]);

                if (state[1] != null) {
                    _editIndex = (int)state[1];
                }

                if (state[2] != null) {
                    _selectedIndex = (int)state[2];
                }

                if (state[3] != null) {
                    _groupItemCount = (int)state[3];
                }

                if (state[4] != null) {
                    _sortExpression = (string)state[4];
                }

                if (state[5] != null) {
                    _sortDirection = (SortDirection)state[5];
                }

                if (state[6] != null) {
                    _dataKeyNames = (string[])state[6];
                }

                if (state[7] != null) {
                    LoadDataKeysState(state[7]);
                }

                if (state[8] != null) {
                    _totalRowCount = (int)state[8];
                }

                if (state[9] != null) {
                    if ((_dataKeyNames != null) && (_dataKeyNames.Length > 0)) {
                        _persistedDataKey = new DataKey(new OrderedDictionary(_dataKeyNames.Length), _dataKeyNames);
                        ((IStateManager)_persistedDataKey).LoadViewState(state[9]);
                    }
                }

                if (state[10] != null) {
                    _clientIDRowSuffix = (string[])state[10];
                }

                if (state[11] != null) {
                    LoadClientIDRowSuffixDataKeysState(state[11]);
                }
                if (state[12] != null) {
                    _startRowIndex = (int)state[12];
                }
                if (state[13] != null) {
                    _maximumRows = (int)state[13];
                }

            }
            else {
                base.LoadControlState(null);
            }
            // DataPager handles the TotalRowCountAvailable event in order to create its pager fields.  Normally this
            // is fired from CreateChildControls, but when ViewState is disabled this is not getting called until after
            // postback data has been handled.  In this case the event will be fired using the control count from the
            // last request so that the pager fields can be initialized.
            if (!IsViewStateEnabled) {
                OnTotalRowCountAvailable(new PageEventArgs(_startRowIndex, _maximumRows, _totalRowCount));
            }
        }

        private void LoadDataKeysState(object state) {
            if (state != null) {
                object[] dataKeysState = (object[])state;
                string[] dataKeyNames = DataKeyNamesInternal;
                int dataKeyNamesLength = dataKeyNames.Length;

                ClearDataKeys();
                for (int i = 0; i < dataKeysState.Length; i++) {
                    DataKeysArrayList.Add(new DataKey(new OrderedDictionary(dataKeyNamesLength), dataKeyNames));
                    ((IStateManager)DataKeysArrayList[i]).LoadViewState(dataKeysState[i]);
                }
            }
        }

        protected override void LoadViewState(object savedState) {
            if (savedState != null) {
                object[] state = (object[])savedState;

                base.LoadViewState(state[0]);
                if (state[1] != null) {
                    OrderedDictionaryStateHelper.LoadViewState((OrderedDictionary)BoundFieldValues, (ArrayList)state[1]);
                }
            }
            else {
                base.LoadViewState(savedState);
            }
        }

        private void LoadClientIDRowSuffixDataKeysState(object state) {
            if (state != null) {
                object[] ClientIDRowSuffixDataKeysState = (object[])state;
                string[] ClientIDRowSuffix = ClientIDRowSuffixInternal;
                int ClientIDRowSuffixLength = ClientIDRowSuffix.Length;

                _clientIDRowSuffixArrayList = null;

                for (int i = 0; i < ClientIDRowSuffixDataKeysState.Length; i++) {
                    ClientIDRowSuffixArrayList.Add(new DataKey(new OrderedDictionary(ClientIDRowSuffixLength), ClientIDRowSuffix));
                    ((IStateManager)ClientIDRowSuffixArrayList[i]).LoadViewState(ClientIDRowSuffixDataKeysState[i]);
                }
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "1#")]
        protected override bool OnBubbleEvent(object source, EventArgs e) {
            bool causesValidation = false;
            string validationGroup = String.Empty;

            ListViewCommandEventArgs commandEventArgs = e as ListViewCommandEventArgs;
            // todo: rethink this.  Should everything in the layout template be bubbled
            // up as a ListViewCommand?
            if (commandEventArgs == null && e is CommandEventArgs) {
                // Use a new EmptyItem ListViewItem here so when HandleEvent tries to parse out the data item index,
                // the user gets a nice message about how this button should be in a data item.
                commandEventArgs = new ListViewCommandEventArgs(new ListViewItem(ListViewItemType.EmptyItem), source, (CommandEventArgs)e);
            }

            if (commandEventArgs != null) {
                IButtonControl button = commandEventArgs.CommandSource as IButtonControl;
                if (button != null) {
                    causesValidation = button.CausesValidation;
                    validationGroup = button.ValidationGroup;
                }
            }
            return HandleEvent(commandEventArgs, causesValidation, validationGroup);
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected internal override void OnInit(EventArgs e) {
            base.OnInit(e);

            if (Page != null) {
                if (DataKeyNames.Length > 0) {
                    Page.RegisterRequiresViewStateEncryption();
                }
                Page.RegisterRequiresControlState(this);
            }

            if (!DesignMode && !String.IsNullOrEmpty(ItemType)) {
                DataBoundControlHelper.EnableDynamicData(this, ItemType);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='CancelCommand '/>event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemCanceling(ListViewCancelEventArgs e) {
            EventHandler<ListViewCancelEventArgs> handler = (EventHandler<ListViewCancelEventArgs>)Events[EventItemCanceling];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "ItemCanceling"));
                }
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='ItemCommand'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemCommand(ListViewCommandEventArgs e) {
            EventHandler<ListViewCommandEventArgs> handler = (EventHandler<ListViewCommandEventArgs>)Events[EventItemCommand];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='ItemCreated'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemCreated(ListViewItemEventArgs e) {
            EventHandler<ListViewItemEventArgs> handler = (EventHandler<ListViewItemEventArgs>)Events[EventItemCreated];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='ItemDataBound'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemDataBound(ListViewItemEventArgs e) {
            EventHandler<ListViewItemEventArgs> handler = (EventHandler<ListViewItemEventArgs>)Events[EventItemDataBound];
            if (handler != null) {
                handler(this, e);
            }

            // EventWizardListItemDataBound is a key for an internal event declared on IWizardSideBarListControl, which is
            // an interface that is meant to provide a facade to make ListView and DataList look the same. This handler
            // is meant to abstract away the differences between each controls ItemDataBound events.
            var wizardListHandler = (EventHandler<WizardSideBarListControlItemEventArgs>)Events[EventWizardListItemDataBound];
            if (wizardListHandler != null) {
                var item = e.Item;
                var wizardListEventArgs = new WizardSideBarListControlItemEventArgs(new WizardSideBarListControlItem(item.DataItem, ListItemType.Item, item.DataItemIndex, item));
                wizardListHandler(this, wizardListEventArgs);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='ItemDeleted '/>event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemDeleted(ListViewDeletedEventArgs e) {
            EventHandler<ListViewDeletedEventArgs> handler = (EventHandler<ListViewDeletedEventArgs>)Events[EventItemDeleted];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='Delete'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemDeleting(ListViewDeleteEventArgs e) {
            EventHandler<ListViewDeleteEventArgs> handler = (EventHandler<ListViewDeleteEventArgs>)Events[EventItemDeleting];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "ItemDeleting"));
                }
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='EditCommand'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemEditing(ListViewEditEventArgs e) {
            EventHandler<ListViewEditEventArgs> handler = (EventHandler<ListViewEditEventArgs>)Events[EventItemEditing];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "ItemEditing"));
                }
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='ItemInserted '/>event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemInserted(ListViewInsertedEventArgs e) {
            EventHandler<ListViewInsertedEventArgs> handler = (EventHandler<ListViewInsertedEventArgs>)Events[EventItemInserted];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='Delete'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemInserting(ListViewInsertEventArgs e) {
            EventHandler<ListViewInsertEventArgs> handler = (EventHandler<ListViewInsertEventArgs>)Events[EventItemInserting];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "ItemInserting"));
                }
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='ItemUpdated '/>event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemUpdated(ListViewUpdatedEventArgs e) {
            EventHandler<ListViewUpdatedEventArgs> handler = (EventHandler<ListViewUpdatedEventArgs>)Events[EventItemUpdated];
            if (handler != null) handler(this, e);
        }

        /// <devdoc>
        /// <para>Raises the <see langword='UpdateCommand'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnItemUpdating(ListViewUpdateEventArgs e) {
            EventHandler<ListViewUpdateEventArgs> handler = (EventHandler<ListViewUpdateEventArgs>)Events[EventItemUpdating];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "ItemUpdating"));
                }
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='LayoutCreated'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnLayoutCreated(EventArgs e) {
            EventHandler handler = (EventHandler)Events[EventLayoutCreated];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='PagePropertiesChanged'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnPagePropertiesChanged(EventArgs e) {
            EventHandler handler = (EventHandler)Events[EventPagePropertiesChanged];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='PagePropertiesChanging'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnPagePropertiesChanging(PagePropertiesChangingEventArgs e) {
            EventHandler<PagePropertiesChangingEventArgs> handler = (EventHandler<PagePropertiesChangingEventArgs>)Events[EventPagePropertiesChanging];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see cref='System.Web.UI.WebControls.ListView.TotalRowCountAvailable'/>event of a <see cref='System.Web.UI.WebControls.ListView'/>.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnTotalRowCountAvailable(PageEventArgs e) {
            EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)Events[EventTotalRowCountAvailable];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see cref='System.Web.UI.WebControls.ListView.SelectedIndexChanged'/>event of a <see cref='System.Web.UI.WebControls.ListView'/>.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnSelectedIndexChanged(EventArgs e) {            
            EventHandler handler = (EventHandler)Events[EventSelectedIndexChanged];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see cref='System.Web.UI.WebControls.ListView.SelectedIndexChanging'/>event of a <see cref='System.Web.UI.WebControls.ListView'/>.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnSelectedIndexChanging(ListViewSelectEventArgs e) {
            EventHandler<ListViewSelectEventArgs> handler = (EventHandler<ListViewSelectEventArgs>)Events[EventSelectedIndexChanging];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "SelectedIndexChanging"));
                }
            }
        }

        /// <devdoc>
        /// <para>Raises the <see cref='System.Web.UI.WebControls.ListView.Sorted'/>event of a <see cref='System.Web.UI.WebControls.ListView'/>.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnSorted(EventArgs e) {
            EventHandler handler = (EventHandler)Events[EventSorted];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// <para>Raises the <see langword='SortCommand'/> event.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnSorting(ListViewSortEventArgs e) {
            EventHandler<ListViewSortEventArgs> handler = (EventHandler<ListViewSortEventArgs>)Events[EventSorting];
            if (handler != null) {
                handler(this, e);
            }
            else {
                if (IsDataBindingAutomatic == false && e.Cancel == false) {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_UnhandledEvent, ID, "Sorting"));
                }
            }
        }

        private bool PageIsValidAfterModelException() {
            if (_modelValidationGroup == null) {
                return true;
            }
            Page.Validate(_modelValidationGroup);
            return Page.IsValid;
        }

        /// <summary>
        /// Overriden by DataBoundControl to use its properties to determine the real
        /// data source that the control should bind to. It then clears the existing
        /// control hierarchy, and calls createChildControls to create a new control
        /// hierarchy based on the resolved data source.
        /// The implementation resolves various data source related properties to
        /// arrive at the appropriate IEnumerable implementation to use as the real
        /// data source.
        /// When resolving data sources, the DataSourceControlID takes highest precedence.
        /// In this mode, DataMember is used to access the appropriate list from the
        /// DataControl.
        /// If DataSourceControlID is not set, the value of the DataSource property is used.
        /// In this second alternative, DataMember is used to extract the appropriate
        /// list if the control has been handed an IListSource as a data source.
        /// </summary>
        protected internal override void PerformDataBinding(IEnumerable data) {
            base.PerformDataBinding(data);

            TrackViewState();

            int controlCount = CreateChildControls(data, true);
            ChildControlsCreated = true;
            ViewState[ItemCountViewStateKey] = controlCount;

            int editIndex = EditIndex;
            if (IsDataBindingAutomatic && editIndex != -1 && editIndex < Items.Count && IsViewStateEnabled) {
                BoundFieldValues.Clear();
                ExtractItemValues(BoundFieldValues, Items[editIndex], false/*includePrimaryKey*/);
            }

            if (EnablePersistedSelection) {
                string[] keyNames = DataKeyNamesInternal;
                //we can't have persisted selection without having at least one key name
                if ((keyNames == null) || (keyNames.Length == 0)) {
                    throw new InvalidOperationException(AtlasWeb.ListView_PersistedSelectionRequiresDataKeysNames);
                }
            }
        }

        protected override void PerformSelect() {
            if (_performingSelect) {
                // Guard against databinding twice if we're currently databinding.
                // This happens when the ListView is nested within a databound control, and the call
                // To EnsureLayoutTemplate triggers a recursive DataBind.
                return;
            }

            try {
                _performingSelect = true;

                // If there is a DataPager in the layout template, we need the ListView's paging properties
                // to be set before we go to the datasource
                EnsureLayoutTemplate();

                if (DesignMode) {
                    // Try to find a pager that will control the paging on this control.
                    // In design mode, an embedded pager will not have a designer but will
                    // be the runtime control itself.  We want the max rows so the ListView
                    // renders with the right page size.
                    DataPager pager = FindDataPager(this);
                    if (pager != null) {
                        _maximumRows = pager.PageSize;
                    }
                }

                base.PerformSelect();
            }
            finally {
                _performingSelect = false;
            }
        }

        protected virtual void RemoveItems() {
            if (_groupTemplate != null) {
                // If we're in grouped mode, delete all the items created in CreateItemsInGroups().
                if (_groupsItemCreatedCount > 0) {
                    for (int i = 0; i < _groupsItemCreatedCount; i++) {
                        _groupsGroupPlaceholderContainer.Controls.RemoveAt(_groupsOriginalIndexOfGroupPlaceholderInContainer);
                    }
                    _groupsItemCreatedCount = 0;
                }
            }
            else {
                // If we're not in grouped mode, delete all the items
                // created in CreateItemsWithoutGroups().
                if (_noGroupsItemCreatedCount > 0) {
                    for (int i = 0; i < _noGroupsItemCreatedCount; i++) {
                        _noGroupsItemPlaceholderContainer.Controls.RemoveAt(_noGroupsOriginalIndexOfItemPlaceholderInContainer);
                    }
                    _noGroupsItemCreatedCount = 0;
                }
            }
            _autoIDIndex = 0;
        }

        protected internal override void Render(HtmlTextWriter writer) {
            // Render only the contents.  We don't want a rendered span tag around the control.
            RenderContents(writer);
        }

        private void ResetModelValidationGroup(bool causesValidation, string validationGroup) {
            _modelValidationGroup = null;
            if (causesValidation) {
                Page.Validate(validationGroup);
                if (EnableModelValidation) {
                    _modelValidationGroup = validationGroup;
                }
            }
        }

        /// <devdoc>
        /// <para>Saves the control state for those properties that should persist across postbacks
        ///   even when EnableViewState=false.</para>
        /// </devdoc>
        protected internal override object SaveControlState() {
            object baseState = base.SaveControlState();
            if (baseState != null ||
                _startRowIndex > 0 ||
                _maximumRows != -1 ||
                _editIndex != -1 ||
                _selectedIndex != -1 ||
                _groupItemCount != 1 ||
                (_sortExpression != null && _sortExpression.Length != 0) ||
                _sortDirection != SortDirection.Ascending ||
                _totalRowCount != -1 ||
                (_dataKeyNames != null && _dataKeyNames.Length != 0) ||
                (_dataKeysArrayList != null && _dataKeysArrayList.Count > 0)) {

                object[] state = new object[14];

                state[0] = baseState;
                state[1] = (_editIndex == -1) ? null : (object)_editIndex;
                state[2] = (_selectedIndex == -1) ? null : (object)_selectedIndex;
                state[3] = (_groupItemCount == 1) ? null : (object)_groupItemCount;
                state[4] = (_sortExpression == null || _sortExpression.Length == 0) ? null : (object)_sortExpression;
                state[5] = (_sortDirection == SortDirection.Ascending) ? null : (object)((int)_sortDirection);
                state[6] = (_dataKeyNames == null || _dataKeyNames.Length == 0) ? null : (object)_dataKeyNames;
                state[7] = SaveDataKeysState();
                state[8] = (_totalRowCount == -1) ? null : (object)_totalRowCount;
                state[9] = (_persistedDataKey == null) ? null :
                    ((IStateManager)_persistedDataKey).SaveViewState();
                state[10] = (_clientIDRowSuffix == null || _clientIDRowSuffix.Length == 0) ? null : (object)_clientIDRowSuffix;
                state[11] = SaveClientIDRowSuffixDataKeysState();
                state[12] = _startRowIndex;
                state[13] = _maximumRows;

                return state;
            }
            return true;    // return a dummy that ensures LoadControlState gets called but minimizes persisted size.
        }

        private object SaveDataKeysState() {
            object keyState = new object();
            int dataKeyCount = 0;

            if (_dataKeysArrayList != null && _dataKeysArrayList.Count > 0) {
                dataKeyCount = _dataKeysArrayList.Count;
                keyState = new object[dataKeyCount];
                for (int i = 0; i < dataKeyCount; i++) {
                    ((object[])keyState)[i] = ((IStateManager)_dataKeysArrayList[i]).SaveViewState();
                }
            }
            return (_dataKeysArrayList == null || dataKeyCount == 0) ? null : keyState;
        }

        protected override object SaveViewState() {
            object baseState = base.SaveViewState();
            object boundFieldValuesState = (_boundFieldValues != null) ? OrderedDictionaryStateHelper.SaveViewState(_boundFieldValues) : null;

            object[] state = new object[2];
            state[0] = baseState;
            state[1] = boundFieldValuesState;

            return state;
        }

        private object SaveClientIDRowSuffixDataKeysState() {
            object keyState = new object();
            int dataKeyCount = 0;
            if (_clientIDRowSuffixArrayList != null && _clientIDRowSuffixArrayList.Count > 0) {
                dataKeyCount = _clientIDRowSuffixArrayList.Count;
                keyState = new object[dataKeyCount];
                for (int i = 0; i < dataKeyCount; i++) {
                    ((object[])keyState)[i] = ((IStateManager)_clientIDRowSuffixArrayList[i]).SaveViewState();
                }
            }
            return (_clientIDRowSuffixArrayList == null || dataKeyCount == 0) ? null : keyState;
        }

        private void SelectCallback(IEnumerable data) {
            // The data source should have thrown.  If we're here, it didn't.  We'll throw for it
            // with a generic message.
            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.ListView_DataSourceDoesntSupportPaging, DataSourceID));
        }

        private void SetRequiresDataBindingIfInitialized() {
            if (Initialized) {
                RequiresDataBinding = true;
            }
        }

        public virtual void Sort(string sortExpression, SortDirection sortDirection) {
            HandleSort(sortExpression, sortDirection);
        }

        public virtual void UpdateItem(int itemIndex, bool causesValidation) {
            ResetModelValidationGroup(causesValidation, String.Empty);
            HandleUpdate(null, itemIndex, causesValidation);
        }

        internal override void UpdateModelDataSourceProperties(ModelDataSource modelDataSource) {
            Debug.Assert(modelDataSource != null, "A non-null ModelDataSource should be passed in");
            string dataKeyName = DataKeyNamesInternal.Length > 0 ? DataKeyNamesInternal[0] : "";
            modelDataSource.UpdateProperties(ItemType, SelectMethod, UpdateMethod, InsertMethod, DeleteMethod, dataKeyName);
        }

        #region IPageableItemContainer
        int IPageableItemContainer.StartRowIndex {
            get {
                return StartRowIndex;
            }
        }

        // Overridable version
        protected virtual int StartRowIndex {
            get {
                return _startRowIndex;
            }
        }

        int IPageableItemContainer.MaximumRows {
            get {
                return MaximumRows;
            }
        }

        // Overridable version
        protected virtual int MaximumRows {
            get {
                return _maximumRows;
            }
        }

        void IPageableItemContainer.SetPageProperties(int startRowIndex, int maximumRows, bool databind) {
            SetPageProperties(startRowIndex, maximumRows, databind);
        }

        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
            Justification = "A property already exists. This method does additional work.")]
        public void SelectItem(int rowIndex) {
            HandleSelect(rowIndex);
        }

        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
            Justification = "A property already exists. This method does additional work.")]
        public void SetEditItem(int rowIndex) {
            HandleEdit(rowIndex);
        }

        // Overridable version
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "databind",
            Justification = "Cannot change to 'dataBind' as would break binary compatibility with legacy code.")]
        protected virtual void SetPageProperties(int startRowIndex, int maximumRows, bool databind) {
            if (maximumRows < 1) {
                throw new ArgumentOutOfRangeException("maximumRows");
            }
            if (startRowIndex < 0) {
                throw new ArgumentOutOfRangeException("startRowIndex");
            }

            if (_startRowIndex != startRowIndex || _maximumRows != maximumRows) {
                PagePropertiesChangingEventArgs args = new PagePropertiesChangingEventArgs(startRowIndex, maximumRows);
                if (databind) {
                    // This event is cancellable, and its properties aren't settable, because changing them would
                    // create a strange disconnect between the pager and the ListView.  You have to set
                    // these properties on the pager if you want to change them.  This is a notification event.
                    OnPagePropertiesChanging(args);
                }

                _startRowIndex = args.StartRowIndex;
                _maximumRows = args.MaximumRows;

                if (databind) {
                    OnPagePropertiesChanged(EventArgs.Empty);
                }
            }

            if (databind) {
                RequiresDataBinding = true;
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes",
                         Justification = "Unlikely that a derived type would re-implement this event.")]
        event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable {
            add {
                Events.AddHandler(EventTotalRowCountAvailable, value);
            }
            remove {
                Events.RemoveHandler(EventTotalRowCountAvailable, value);
            }
        }
        #endregion IPageableItemContainer

        #region IPersistedSelector implementation

        DataKey IPersistedSelector.DataKey {
            get {
                return SelectedPersistedDataKey;
            }
            set {
                SelectedPersistedDataKey = value;
            }
        }
        #endregion

        #region IDataKeysControl implementation
        DataKeyArray IDataKeysControl.ClientIDRowSuffixDataKeys {
            get {
                return ClientIDRowSuffixDataKeys;
            }
        }
        #endregion

        #region IDataBoundListControl implementation

        DataKeyArray IDataBoundListControl.DataKeys {
            get { 
                return DataKeys; 
            }
        }

        DataKey IDataBoundListControl.SelectedDataKey {
            get { 
                return SelectedDataKey; 
            }
        }

        int IDataBoundListControl.SelectedIndex {
            get {
                return SelectedIndex;
            }
            set {
                SelectedIndex = value;
            }
        }

        string[] IDataBoundListControl.ClientIDRowSuffix {
            get {
                return ClientIDRowSuffix;
            }
            set {
                ClientIDRowSuffix = value;
            }
        }

        bool IDataBoundListControl.EnablePersistedSelection {
            get {
                return EnablePersistedSelection;
            }
            set {
                EnablePersistedSelection = value;
            }
        }

        string IDataBoundControl.DataSourceID {
            get {
                return DataSourceID;
            }
            set {
                DataSourceID = value;
            }
        }

        IDataSource IDataBoundControl.DataSourceObject {
            get { 
                return DataSourceObject; 
            }
        }

        object IDataBoundControl.DataSource {
            get {
                return DataSource;
            }
            set {
                DataSource = value;
            }
        }

        string[] IDataBoundControl.DataKeyNames {
            get {
                return DataKeyNames;
            }
            set {
                DataKeyNames = value;
            }
        }

        string IDataBoundControl.DataMember {
            get {
                return DataMember;
            }
            set {
                DataMember = value;
            }
        }

        #endregion

        #region IWizardSideBarListControl implementation

        IEnumerable IWizardSideBarListControl.Items {
            get { return Items; }
        }

        event CommandEventHandler IWizardSideBarListControl.ItemCommand {
            add {
                ItemCommand += new EventHandler<ListViewCommandEventArgs>(value);
            }
            remove {
                ItemCommand -= new EventHandler<ListViewCommandEventArgs>(value);
            }

        }

        event EventHandler<WizardSideBarListControlItemEventArgs> IWizardSideBarListControl.ItemDataBound {
            add {
                Events.AddHandler(EventWizardListItemDataBound, value);
            }
            remove {
                Events.RemoveHandler(EventWizardListItemDataBound, value);
            }
        }

        #endregion
    }
}