diff --git a/WinFormSolution/Components/UserControlCheckedList.cs b/WinFormSolution/Components/UserControlCheckedList.cs index 018025a..e18ff56 100644 --- a/WinFormSolution/Components/UserControlCheckedList.cs +++ b/WinFormSolution/Components/UserControlCheckedList.cs @@ -2,6 +2,8 @@ { public partial class UserControlCheckedList : UserControl { + private List _lastCheckedIndexes = new List(); + public int MaxCheckedItemsCount { get; set; } = 1; private EventHandler _onCheckedItemChangedEvent; public event EventHandler CheckedItemChanged { @@ -43,16 +45,24 @@ public void ClearCheckedListBoxValues() { checkedListBox.Items.Clear(); + _lastCheckedIndexes.Clear(); } private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e) { - for (int i = 0; i < checkedListBox.Items.Count; i++) + if (e.NewValue == CheckState.Checked) { - if (i != e.Index) + _lastCheckedIndexes.Add(e.Index); + + while (_lastCheckedIndexes.Count > MaxCheckedItemsCount) { - checkedListBox.SetItemChecked(i, false); + checkedListBox.SetItemCheckState(_lastCheckedIndexes[0], CheckState.Unchecked); } } + else if (e.NewValue == CheckState.Unchecked) + { + _lastCheckedIndexes.Remove(e.Index); + } + _onCheckedItemChangedEvent?.Invoke(sender, e); } }