简体   繁体   中英

How to check range in checkedlistbox c# winforms?

I have a checkeboxlist with 100 items. Obviously user can check items one by one as many as he need, but I would like to give to user option check range of items (let's say with Shift hold button). So, user check one of the items (let's say item index 5) and then press and hold shift button and check next item (index 10), so I range of the items should be checked from 5...10

I have not found anything about such implementation, looks like it doesn't exist and no one did such kind of things.

How to do it?

Keep track of your last index:

int lastIndex = -1;

In your form's constructor, wire things up:

public Form1() {
  InitializeComponent();

  checkedListBox1.CheckOnClick = true;
  checkedListBox1.SelectedIndexChanged += CheckedListBox1_SelectedIndexChanged;
  checkedListBox1.MouseDown += CheckedListBox1_MouseDown;
}

And then use these methods to change the items in the range:

private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e) {
  lastIndex = checkedListBox1.SelectedIndex;
}

private void CheckedListBox1_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left && Control.ModifierKeys == Keys.Shift) {
    var useIndex = Math.Max(lastIndex, 0);
    var x = checkedListBox1.IndexFromPoint(e.Location);
    if (x > -1 && x != useIndex) {
      if (useIndex > x) {
        for (int i = useIndex - 1; i > x; i--) {
          checkedListBox1.SetItemChecked(i, !checkedListBox1.GetItemChecked(i));
        }
      } else {
        for (int i = useIndex + 1; i < x; i++) {
          checkedListBox1.SetItemChecked(i, !checkedListBox1.GetItemChecked(i));
        }
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM