【问题标题】:When I move through a list box, why do my checked items become unchecked?当我在列表框中移动时,为什么我的选中项变为未选中?
【发布时间】:2009-01-04 00:09:01
【问题描述】:

下面的代码将列表框中的选定项向下移动到列表框中的下一项,但如果选定项被选中,它将取消选中。我怎样才能防止这种情况发生?

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

谢谢

moveListboxItem的代码如下:

 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;
}

【问题讨论】:

  • 您需要发布 moveListBoxItem 的来源以便我们能够提供帮助

标签: c# winforms listbox checkedlistbox


【解决方案1】:

您需要发布 moveListBoxItem 的代码,以便我们能够提供帮助。

我怀疑 moveListBoxItem 看起来像这样。

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

如果是这种情况,它不起作用的原因是,一旦你删除了对象,CheckedListBox 就不再跟踪特定索引的选中状态。您需要稍后重新添加它。

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);
}

编辑:更新实际 moveListBoxItem 代码。您还需要将 CheckState 传播到新索引。从集合中删除它实质上会清除存储的状态。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多