When I navigate through the list box, why do my checked items become unchecked?

The code below moves the selected item in the list down to the next item in the list, but it overrides the selected item if it was checked. How can I prevent this?

private void buttonMoveDown_Click(object sender, EventArgs e)
{
   int iIndex = checkedListBox1.SelectedIndex;
   if (iIndex == -1)
   {
      return;
   }
   moveListboxItem(checkedListBox1,  iIndex, iIndex + 1);
}

      

thank

The code for moveListboxItem looks like this:

 private void moveListboxItem(CheckedListBox ctl, int fromIndex,int toIndex)
        {
            if(fromIndex == toIndex)
            {
                return;
            }
            if(fromIndex < 0 )
            {
                fromIndex = ctl.SelectedIndex;
            }
            if(toIndex < 0 || toIndex > ctl.Items.Count - 1)
            {
                return;
            }

            object data = ctl.Items[fromIndex];
            ctl.Items.RemoveAt(fromIndex);
            ctl.Items.Insert(toIndex, data);
            ctl.SelectedIndex = toIndex;
}

      

0


source to share


1 answer


You will need to post the code for moveListBoxItem so we can help.

My suspicion is that moveListBoxItem looks something like this.

void moveListBoxItem(CheckedListBox list, int oldIndex, int newIndex ) {
  object old = list.Items[oldIndex];
  list.Items.RemoveAt(oldIndex);
  list.Items.Insert(newIndex, old);
}

      

If so, the reason it doesn't work is because after deleting the object, the CheckedListBox no longer keeps track of the checked state of a particular index. You will need to add this again later.



void moveListBoxItem(CheckedListBox list, int oldIndex, int newIndex ) {
  var state = list.GetItemCheckedState(oldIndex);
  object old = list.Items[oldIndex];
  list.Items.RemoveAt(oldIndex);
  list.Items.Insert(newIndex, old);
  list.SetItemCheckedState(newIndex, state);
}

      

EDIT: Update for the actual moveListBoxItem code. You need to propagate CheckState to the new index as well. Deleting from the collection substantially clears the saved state.

private void moveListboxItem(CheckedListBox ctl, int fromIndex,int toIndex)
        {
            if(fromIndex == toIndex)
            {
                return;
            }
            if(fromIndex < 0 )
            {
                fromIndex = ctl.SelectedIndex;
            }
            if(toIndex < 0 || toIndex > ctl.Items.Count - 1)
            {
                return;
            }

            object data = ctl.Items[fromIndex];
            CheckState state = ctl.GetItemCheckState(fromIndex);
            ctl.Items.RemoveAt(fromIndex);
            ctl.Items.Insert(toIndex, data);
            ctl.SetItemCheckState(toIndex, state);
            ctl.SelectedIndex = toIndex;
}

      

+3


source







All Articles