-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListView.cs
957 lines (829 loc) · 27.5 KB
/
ListView.cs
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
// Bindable list view.
// 2003 - Ian Griffiths (ian@interact-sw.co.uk)
//
// This code is in the public domain, and has no warranty.
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace Want.Components
{
/// <summary>
/// A ListView with complex data binding support.
/// </summary>
/// <remarks>
/// <p>Windows Forms provides a built-in <see cref="ListView"/> control,
/// which is essentially a wrapper of the standard Win32 list view. While
/// this is a very powerful control, it does not support complex data
/// binding. It supports simple binding, as all controls do, but simple
/// binding only binds a single row of data. The absence of complex
/// binding (i.e. the ability to bind to whole lists of data) is
/// disappointing in a class whose main purpose is to display lists of
/// things.</p>
///
/// <p>This class derives from <see cref="ListView"/> and adds support
/// for complex binding, through its <see cref="DataSource"/> and
/// <see cref="DataMember"/> properties. These behave much like the
/// equivalent properties on the =<see cref="DataGrid"/> control.</p>
///
/// <p>Note that the primary purpose of this control is to illustrate
/// data binding implementation techniques. It is NOT designed as an
/// industrial-strength control for use in production code. If you use
/// this in live systems, you do so at your own risk; it would almost
/// certainly be a better idea to look at the various professional
/// bindable grid controls on the market.</p>
///
/// From http://www.interact-sw.co.uk/utilities/
/// Extended by filtering ideas from http://www.codeproject.com/cs/miscctrl/listviewfilter.asp
///
/// Document: order of fields is directly linked to order of element nodes in Dataset XML
/// which themselves are independent of order in db table schema!
///
/// If column headers contain less columns than fields in dataset, the listview item still has
/// all data as subitems, but not everything is display => put ID fields to the end of the
/// SdmDataset XSD
///
///
/// </remarks>
public class ListView : System.Windows.Forms.ListView
{
public ListView()
{
ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(HandleColumnClick);
ListViewItemSorter = new ListViewItemComparer();
alFilteredItems = new ArrayList();
}
private int m_idColumn;
public int IdColumn
{
get
{
return m_idColumn;
}
set
{
m_idColumn = value;
}
}
public string SelectedID
{
get
{
if (SelectedIndices.Count > 0)
{
return SelectedItems[0].SubItems[IdColumn].Text;
}
else
{
return "";
}
}
}
public void AddMatchCriteria(int col, string filterValue)
{
if ((criteria != null) && (criteria.Length > col))
{
criteria[col] = filterValue;
DoFiltering();
}
}
public void ResetMatchCriteria()
{
if (criteria == null)
{
return;
}
for (int i = 0; i < criteria.Length; i++)
{
criteria[i] = "";
}
DoFiltering();
}
/*
public string MustMatchCriteria
{
get
{
return m_filter;
}
set
{
m_filter = value;
DoFiltering();
}
}
private int m_filtercol;
public int MustMatchColumn
{
get
{
return m_filtercol;
}
set
{
m_filtercol = value;
DoFiltering();
}
}
*/
private ArrayList alFilteredItems;
private String[] criteria;
private void DoFiltering()
{
if ((criteria == null) ||(criteria.Length == 0))
{
return;
}
BeginUpdate();
ListViewItem l;
// check current list, take out elements
for ( int i = 0; i < this.Items.Count; ++i )
{
// get the item to check against the filters
l = this.Items[i];
bool meetsAll = true;
for (int j = 0; j < l.SubItems.Count; j++)
{
if ((criteria[j] != null) && (criteria[j].Length > 0))
{
String s = l.SubItems[j].Text;
if (!s.ToUpper().Equals(criteria[j].ToUpper()))
{
meetsAll = false;
}
}
}
if (!meetsAll)
{
alFilteredItems.Add(l);
Items.RemoveAt(i--);
}
}
for ( int i = 0; i < alFilteredItems.Count; ++i )
{
l = (ListViewItem)alFilteredItems[i];
bool meetsAll = true;
for (int j = 0; j < l.SubItems.Count; j++)
{
if ((criteria[j] != null) && (criteria[j].Length > 0))
{
String s = l.SubItems[j].Text;
if (!s.ToUpper().Equals(criteria[j].ToUpper()))
{
meetsAll = false;
}
}
}
if (meetsAll)
{
Items.Add(l);
alFilteredItems.RemoveAt(i--);
}
}
EndUpdate();
}
/// <summary>
/// The data source to which this control is bound.
/// </summary>
/// <remarks>
/// <p>To make this control display the contents of a data source, you
/// should set this property to refer to that data source. The source
/// should implement either <see cref="IList"/>,
/// <see cref="IBindingList"/>, or <see cref="IListSource"/>.</p>
///
/// <p>When binding to a list container (i.e. one that implements the
/// <see cref="IListSource"/> interface, such as <see cref="DataSet"/>)
/// you must also set the <see cref="DataMember"/> property in order
/// to identify which particular list you would like to display. You
/// may also set the <see cref="DataMember"/> property even when
/// DataSource refers to a list, since <see cref="DataMember"/> can
/// also be used to navigate relations between lists.</p>
/// </remarks>
[Category("Data")]
[TypeConverter(
"System.Windows.Forms.Design.DataSourceConverter, System.Design")]
public object DataSource
{
get
{
return m_dataSource;
}
set
{
if (m_dataSource != value)
{
// Must be either a list or a list source
if (value != null && !(value is IList) &&
!(value is IListSource))
{
throw new ArgumentException(
"Data source must be IList or IListSource");
}
m_dataSource = value;
SetDataBinding();
OnDataSourceChanged(EventArgs.Empty);
}
}
}
private object m_dataSource;
/// <summary>
/// Raised when the DataSource property changes.
/// </summary>
public event EventHandler DataSourceChanged;
/// <summary>
/// Called when the DataSource property changes
/// </summary>
/// <param name="e">The EventArgs that will be passed to any handlers
/// of the DataSourceChanged event.</param>
protected virtual void OnDataSourceChanged(EventArgs e)
{
if (DataSourceChanged != null)
DataSourceChanged(this, e);
}
/// <summary>
/// Identifies the item or relation within the data source whose
/// contents should be shown.
/// </summary>
/// <remarks>
/// <p>If the <see cref="DataSource"/> refers to a container of lists
/// such as a <see cref="DataSet"/>, this property should be used to
/// indicate which list should be shown.</p>
///
/// <p>Even when <see cref="DataSource"/> refers to a specific list,
/// you can still set this property to indicate that a related table
/// should be shown by specifying a relation name. This will cause
/// this control to display only those rows in the child table related
/// to the currently selected row in the parent table.</p>
/// </remarks>
[Category("Data")]
[Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design",
typeof(System.Drawing.Design.UITypeEditor))]
public string DataMember
{
get
{
return m_DataMember;
}
set
{
if (m_DataMember != value)
{
m_DataMember = value;
SetDataBinding();
OnDataMemberChanged(EventArgs.Empty);
}
}
}
private string m_DataMember;
/// <summary>
/// Raised when the DataMember property changes.
///</summary>
public event EventHandler DataMemberChanged;
/// <summary>
/// Called when the DataMember property changes.
/// </summary>
/// <param name="e">The EventArgs that will be passed to any handlers
/// of the DataMemberChanged event.</param>
protected virtual void OnDataMemberChanged(EventArgs e)
{
if (DataMemberChanged != null)
DataMemberChanged(this, e);
}
/// <summary>
/// Handles binding context changes
/// </summary>
/// <param name="e">The EventArgs that will be passed to any handlers
/// of the BindingContextChanged event.</param>
protected override void OnBindingContextChanged(EventArgs e)
{
base.OnBindingContextChanged (e);
// If our binding context changes, we must rebind, since we will
// have a new currency managers, even if we are still bound to the
// same data source.
SetDataBinding();
}
/// <summary>
/// Handles parent binding context changes
/// </summary>
/// <param name="e">Unused EventArgs.</param>
protected override void OnParentBindingContextChanged(EventArgs e)
{
base.OnParentBindingContextChanged (e);
// BindingContext is an ambient property - by default it simply picks
// up the parent control's context (unless something has explicitly
// given us our own). So we must respond to changes in our parent's
// binding context in the same way we would changes to our own
// binding context.
SetDataBinding();
}
// Attaches the control to a data source.
private void SetDataBinding()
{
// The BindingContext is initially null - in general we will not
// obtain a BindingContext until we are attached to our parent
// control. (OnParentBindingContextChanged will be called when
// that happens, so this method will run again. This means it's
// OK to ignore this call when we don't yet have a BindingContext.)
if (BindingContext != null)
{
// Obtain the CurrencyManager and (if available) IBindingList
// for the current data source.
CurrencyManager currencyManager = null;
IBindingList bindingList = null;
if (DataSource != null)
{
currencyManager = (CurrencyManager)
BindingContext[DataSource, DataMember];
if (currencyManager != null)
{
bindingList = currencyManager.List as IBindingList;
}
}
// Now see if anything has changed since we last bound to a source.
bool reloadMetaData = false;
bool reloadItems = false;
if (currencyManager != m_currencyManager)
{
// We have a new CurrencyManager. If we were previously
// using another CurrencyManager (i.e. if this is not the
// first time we've seen one), we'll have some event
// handlers attached to the old one, so first we must
// detach those.
if (m_currencyManager != null)
{
currencyManager.MetaDataChanged -=
new EventHandler(currencyManager_MetaDataChanged);
currencyManager.PositionChanged -=
new EventHandler(currencyManager_PositionChanged);
currencyManager.ItemChanged -=
new ItemChangedEventHandler(currencyManager_ItemChanged);
}
// Now hook up event handlers to the new CurrencyManager.
// This enables us to detect when the currently selected
// row changes. It also lets us find out more major changes
// such as binding to a different list object (this happens
// when binding to related views - each time the currently
// selected row in a parent changes, the child list object
// is replaced with a new object), or even changes in the
// set of properties.
m_currencyManager = currencyManager;
if (currencyManager != null)
{
reloadMetaData = true;
reloadItems = true;
currencyManager.MetaDataChanged +=
new EventHandler(currencyManager_MetaDataChanged);
currencyManager.PositionChanged +=
new EventHandler(currencyManager_PositionChanged);
currencyManager.ItemChanged +=
new ItemChangedEventHandler(currencyManager_ItemChanged);
}
}
if (bindingList != m_bindingList)
{
// The IBindingList has changed. If we were previously
// bound to an IBindingList, detach the event handler.
if (m_bindingList != null)
{
m_bindingList.ListChanged -=
new ListChangedEventHandler(bindingList_ListChanged);
}
// Now hook up a handler to the new IBindingList - this
// will notify us of any changes in the list. (This is
// more detailed than the CurrencyManager ItemChanged
// event. However, we need both, because the only way we
// know when the list is replaced completely is when the
// CurrencyManager raises the ItemChanged event.)
m_bindingList = bindingList;
if (bindingList != null)
{
reloadItems = true;
bindingList.ListChanged +=
new ListChangedEventHandler(bindingList_ListChanged);
}
}
// If a change occurred that means the set of properties may
// have changed, reload these.
if (reloadMetaData)
{
//LoadColumnsFromSource();
}
// If a change occurred that means the set of items to be
// shown in the list may have changed, reload those.
if (reloadItems)
{
LoadItemsFromSource();
}
}
}
private CurrencyManager m_currencyManager;
private IBindingList m_bindingList;
private PropertyDescriptorCollection m_properties;
/*
private void LoadColumnsFromSource()
{
// Retrieve and store the PropertyDescriptors. (We always go
// via PropertyDescriptors when binding, and not the Reflection
// API - this allows generic data sources to decide at runtime
// what properties to present.) For data sources that don't opt
// to have dynamic properties, the PropertyDescriptor mechanism
// automatically falls back to Reflection under the covers.
m_properties = m_currencyManager.GetItemProperties();
// Build new column headers for the ListView.
ColumnHeader[] headers = new ColumnHeader[m_properties.Count];
Columns.Clear();
for (int column = 0; column < m_properties.Count; ++column)
{
string columnName = m_properties[column].Name;
// We set the width to be -2 in order to auto-size the column
// to the header text. Bizarrely, this only works if we set
// the width after adding the column. (That's we we're not
// simply passing -2 to Add. The value passed - 0 in this case
// - is irrelevant here.)
Columns.Add(columnName, 0, HorizontalAlignment.Left);
Columns[column].Width = -2;
}
// For some reason we seem to need to go back and set the
// first column's Width to -2 (auto width) a second time.
// It doesn't stick first time.
Columns[0].Width = -2;
}
*/
// Reload list items from the data source.
private void LoadItemsFromSource()
{
// Tell the control not to bother redrawing until we're done
// adding new items - avoids flicker and speeds things up.
BeginUpdate();
m_properties = m_currencyManager.GetItemProperties();
try
{
// We're about to rebuild the list, so get rid of the current
// items.
Items.Clear();
// m_bindingList won't be set if the data source doesn't
// implement IBindingList, so always ask the CurrencyManager
// for the IList. (IList is all we need to retrieve the rows.)
IList items = m_currencyManager.List;
// Add items to list.
int nItems = items.Count;
for (int i = 0; i < nItems; ++i)
{
Items.Add(BuildItemForRow(items[i]));
}
int index = m_currencyManager.Position;
if (index != -1)
{
SetSelectedIndex(index);
}
}
finally
{
// In finally block just in case the data source does something
// nasty to us - it feels like it might be bad to leave the
// control in a state where we called BeginUpdate without a
// corresponding EndUpdate.
EndUpdate();
}
}
// Build a single ListViewItem for a single row from the source. (We
// need to do this when constructing the original list, but this is
// also called in the IBindingList.ListChanged event handler when
// updating individual items.)
private ListViewItem BuildItemForRow(object row)
{
string[] itemText = new string[m_properties.Count];
for (int column = 0; column < itemText.Length; ++column)
{
// Use the PropertyDescriptors to extract the property value -
// this might be a virtual property.
itemText[column] = m_properties[column].GetValue(row).ToString();
}
if ((criteria == null) || (criteria.Length != itemText.Length))
{
criteria = new String[itemText.Length];
}
// assign image index 0 by default
return new ListViewItem(itemText, 0);
}
// IBindingList ListChanged event handler. Deals with fine-grained
// changes to list items.
private void bindingList_ListChanged(object sender,
ListChangedEventArgs e)
{
switch (e.ListChangedType)
{
// Well, usually fine-grained... The whole list has changed
// utterly, so reload it.
case ListChangedType.Reset:
LoadItemsFromSource();
break;
// A single item has changed, so just rebuild that.
case ListChangedType.ItemChanged:
object changedRow = m_currencyManager.List[e.NewIndex];
BeginUpdate();
Items[e.NewIndex] = BuildItemForRow(changedRow);
EndUpdate();
break;
// A new item has appeared, so add that.
case ListChangedType.ItemAdded:
object newRow = m_currencyManager.List[e.NewIndex];
// We get this event twice if certain grid controls
// are used to add a new row to a datatable: once when
// the editing of a new row begins, and once again when
// that editing commits. (If the user cancels the creation
// of the new row, we never see the second creation.)
// We detect this by seeing if this is a view on a
// row in a DataTable, and if it is, testing to see if
// it's a new row under creation.
DataRowView drv = newRow as DataRowView;
if (drv == null || !drv.IsNew)
{
// Either we're not dealing with a view on a data
// table, or this is the commit notification. Either
// way, this is the final notification, so we want
// to add the new row now!
BeginUpdate();
Items.Insert(e.NewIndex, BuildItemForRow(newRow));
EndUpdate();
}
break;
// An item has gone away.
case ListChangedType.ItemDeleted:
if (e.NewIndex < Items.Count)
{
Items.RemoveAt(e.NewIndex);
}
break;
// An item has changed its index.
case ListChangedType.ItemMoved:
BeginUpdate();
ListViewItem moving = Items[e.OldIndex];
Items.Insert(e.NewIndex, moving);
EndUpdate();
break;
// Something has changed in the metadata. (This control is
// too lazy to deal with this in a fine-grained fashion,
// mostly because the author has never seen this event
// occur... So we deal with it the simple way: reload
// everything.)
case ListChangedType.PropertyDescriptorAdded:
case ListChangedType.PropertyDescriptorChanged:
case ListChangedType.PropertyDescriptorDeleted:
//LoadColumnsFromSource();
LoadItemsFromSource();
break;
}
}
// The CurrencyManager calls this if the data source looks
// different. We just reload everything.
private void currencyManager_MetaDataChanged(object sender,
EventArgs e)
{
//LoadColumnsFromSource();
LoadItemsFromSource();
}
// Called by the CurrencyManager when the currently selected item
// changes. We update the ListView selection so that we stay in sync
// with any other controls bound to the same source.
private void currencyManager_PositionChanged(object sender,
EventArgs e)
{
SetSelectedIndex(m_currencyManager.Position);
}
// Change the currently-selected item. (I'm sure I'm missing a simpler
// way of doing this... If anyone knows what it is, please let me
// know!)
private void SetSelectedIndex(int index)
{
// Avoid recursion - we keep track of when we're already in the
// middle of changing the index, in case the CurrencyManager
// decides to call us back as a result of a change already in
// progress. (Not sure if this will ever actually happen - the
// OnSelectedIndexChanged method uses the m_changingIndex flag to
// avoid modifying the CurrencyManager's Position when the change
// in selection was caused by the CurrencyManager in the first
// place. But it doesn't hurt to be defensive...)
if (!m_changingIndex)
{
m_changingIndex = true;
SelectedItems.Clear();
if (Items.Count > index)
{
ListViewItem item = Items[index];
item.Selected = true;
item.EnsureVisible();
}
m_changingIndex = false;
}
}
private bool m_changingIndex;
// Called by Windows Forms when the currently selected index of the
// control changes. This usually happens because the user clicked on
// the control. In this case we want to notify the CurrencyManager so
// that any other bound controls will remain in sync. This method will
// also be called when we changed our index as a result of a
// notification that originated from the CurrencyManager, and in that
// case we avoid notifying the CurrencyManager back!
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged (e);
// Did this originate from us, or was this caused by the
// CurrencyManager in the first place. If we're sure it was us,
// and there is actually a selected item (this event is also raised
// when transitioning to the 'no items selected' state), and we
// definitely do have a CurrencyManager (i.e. we are actually bound
// to a data source), then we notify the CurrencyManager.
if (!m_changingIndex && SelectedIndices.Count > 0 &&
m_currencyManager != null)
{
m_currencyManager.Position = SelectedIndices[0];
}
}
// Called by the CurrencyManager when stuff changes. (Yes I know
// that's vague, but then so is the official documentation.)
// At time of writing, the official docs imply that you don't need
// to handle this event if your source implements IBindingList, since
// IBindingList.ListChanged provides more details information about the
// change. However, it's not quite as simple as that: when bound to a
// related view, the list to which we are bound changes every time the
// selected index of the parent changes, and to see that happen we
// either have handle this event, or the CurrentChanged (also from the
// CurrencyManager). So in practice you need to handle both.
// It doesn't appear to matter whether you handle CurrentChanged or
// ItemChanged in order to detect such changes - both are raised when
// the underlying list changes. However, Mark Boulter sent me some
// example code (thanks Mark!) that used this one, and he probably
// knows something I don't about which is likely to work better...
// So I'm doing what his code does and using this event.
private void currencyManager_ItemChanged(object sender,
ItemChangedEventArgs e)
{
// An index of -1 seems to be the indication that lots has
// changed. (I've not found where it says this in the
// documentation - I got this information from a comment in Mark
// Boulter's code.) So we always reload all items from the
// source when this happens.
if (e.Index == -1)
{
// ...but before we reload all items from source, we also look
// to see if the list we're supposed to bind to has changed
// since last time, and if it has, reattach our event handlers.
if (!object.ReferenceEquals(m_bindingList, m_currencyManager.List))
{
m_bindingList.ListChanged -=
new ListChangedEventHandler(bindingList_ListChanged);
m_bindingList = m_currencyManager.List as IBindingList;
if (m_bindingList != null)
{
m_bindingList.ListChanged +=
new ListChangedEventHandler(bindingList_ListChanged);
}
}
LoadItemsFromSource();
}
}
public void HandleColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
{
if (!(sender is System.Windows.Forms.ListView))
{
return;
}
ListView lv = (ListView)sender;
ListViewItemComparer lvic = (ListViewItemComparer)lv.ListViewItemSorter;
//if (sender.GetType().
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvic.SortColumn)
{
// Reverse the current sort direction for this column.
if (lvic.Order == SortOrder.Ascending)
{
lvic.Order = SortOrder.Descending;
}
else
{
lvic.Order = SortOrder.Ascending;
}
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvic.SortColumn = e.Column;
lvic.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
lv.Sort();
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <remarks>
/// Thanks to Chris Beckett at
/// http://www.codeproject.com/cs/miscctrl/listviewautosize.asp
/// </remarks>
protected override void WndProc( ref Message message )
{
const int WM_PAINT = 0xf ;
// if the control is in details view mode and columns
// have been added, then intercept the WM_PAINT message
// and reset the last column width to fill the list view
switch ( message.Msg )
{
case WM_PAINT:
if ( this.View == System.Windows.Forms.View.Details && this.Columns.Count > 0 )
this.Columns[this.Columns.Count - 1].Width = -2 ;
break ;
}
// pass messages on to the base control for processing
base.WndProc( ref message ) ;
}
// This class is an implementation of the 'IComparer' interface.
public class ListViewItemComparer : IComparer
{
// Specifies the column to be sorted
private int ColumnToSort;
// Specifies the order in which to sort (i.e. 'Ascending').
private SortOrder OrderOfSort;
// Case insensitive comparer object
private CaseInsensitiveComparer ObjectCompare;
// Class constructor, initializes various elements
public ListViewItemComparer()
{
// Initialize the column to '0'
ColumnToSort = 0;
// Initialize the sort order to 'none'
OrderOfSort = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
ObjectCompare = new CaseInsensitiveComparer();
}
// This method is inherited from the IComparer interface.
// It compares the two objects passed using a case
// insensitive comparison.
//
// x: First object to be compared
// y: Second object to be compared
//
// The result of the comparison. "0" if equal,
// negative if 'x' is less than 'y' and
// positive if 'x' is greater than 'y'
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
// Case insensitive Compare
compareResult = ObjectCompare.Compare (
listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text
);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
}
// Gets or sets the number of the column to which to
// apply the sorting operation (Defaults to '0').
public int SortColumn
{
set
{
ColumnToSort = value;
}
get
{
return ColumnToSort;
}
}
// Gets or sets the order of sorting to apply
// (for example, 'Ascending' or 'Descending').
public SortOrder Order
{
set
{
OrderOfSort = value;
}
get
{
return OrderOfSort;
}
}
}
}
}