CheckedListBox只有一个已检查但保持最后

时间:2014-07-03 21:30:36

标签: c# checkbox checked checkedlistbox

我在使CheckedListBox按照我想要的方式运行时遇到了一些困难。我想要完成的是获取一个CheckedListBox,并在PageLoad上选中第一个框。我希望在任何给定时间只检查一个复选框,但我也不希望用户取消选中最后一个复选框。我可以做其中一个,但我似乎无法做到。

以下是我用来完成只检查一个复选框的任务的一些代码段。这些问题是在没有选中复选框的情况下可以取消选中最后一个选项。

第一个片段:

        if(e.NewValue == CheckState.Checked)
        {
            // Uncheck the other items
            for (int i = 0; i < defCheckedListBox.Items.Count; i++)
            {
                if (e.Index != i)
                {
                    this.defCheckedListBox.SetItemChecked(i, false);
                }
            }
        }

第二个片段

        // Ensure that we are checking an item
        if (e.NewValue != CheckState.Checked)
        {
            return;
        }

        // Get the items that are selected
        CheckedListBox.CheckedIndexCollection selectedItems = this.defCheckedListBox.CheckedIndices;

        // Check that we have at least 1 item selected
        if (selectedItems.Count > 0)
        {
            // Uncheck the other item
            this.defCheckedListBox.SetItemChecked(selectedItems[0], false);
        }

以下是我用来阻止最后一个复选框被取消选中&#34;

        if (laborLevelDefCheckedListBox.CheckedItems.Count == 1)
        {
            if (e.CurrentValue == CheckState.Checked)
            {
                e.NewValue = CheckState.Checked;
            }
        }

我知道这必须简单,但我认为因为我已经度过了漫长的一周而且我已经看了太长时间它不会来找我。任何帮助都非常感谢!如果我在周末解决这个问题,我一定会发布我的解决方案。顺便提一下这个美国人的节日快乐:)

2 个答案:

答案 0 :(得分:2)

Chris在评论中提出了一个很好的观点,即你觉得你正在重新发明单选按钮,但如果你真的希望它与CheckedListBox一起使用,那么你几乎已经发布了你发布的代码。我已经调整了你的第一个代码片段中的代码,我认为这样做了:

//remove the event handler so when we change the state of other items the event
//isn't fired again.
defCheckedListBox.ItemCheck -= defCheckedListBox_ItemCheck;

if (e.NewValue == CheckState.Checked)
{
    // Uncheck the other items
    for (int i = 0; i < defCheckedListBox.Items.Count; i++)
    {
        if (e.Index != i)
        {
            this.defCheckedListBox.SetItemChecked(i, false);
        }
    }
 }
 else
 {
     //the state was not checked.
     //as only one item can ever be Checked inside the event
     //handler the state of not checked is invalid for us; set the state back to Checked.
     e.NewValue = CheckState.Checked;
 }

 //re-add the event handler 
 defCheckedListBox.ItemCheck += defCheckedListBox_ItemCheck;

基本上唯一的新部件是else,如果状态未被检查,我们重置状态,并且当我们手动设置其他项目的状态时,移除并重新添加事件以防止它再次触发(如果您愿意,可以使用全局bool处理。)

答案 1 :(得分:0)

// Use CheckBoxList Event
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)  {
    // Stops DeInitialize Event
    checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
    // Get the new value old value my be in Indeterminate State
    checkedListBox1.SetItemCheckState(e.Index, e.NewValue);
    // Start ReInitialize Event
    checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
相关问题