【问题标题】:How to disable a button if all CheckedListbox items are unchecked如果所有 CheckedListbox 项目都未选中,如何禁用按钮
【发布时间】:2014-05-27 09:34:19
【问题描述】:

如果用户取消选中我的 CheckedListBox 中的所有项目,我想禁用一个按钮。先看看我的代码:

void checkedListBoxChannels_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        ...

        if (this.checkedListBoxChannels.CheckedItems.Count == 0) {
            this.btnOK.Enabled = false;
        }
        else {
            this.btnOK.Enabled = true;
        }           
    }

现在的问题是:当我取消选中最后一个复选框并且在 if 块中检查完成时,CheckedItems.Count 仍然是 1,所以按钮不会被禁用。当我在未选中复选框后选中第一个复选框时出现同样的问题。计数为 0,因此我的按钮被禁用。

那么有没有可能找出 CheckedListBox 控件当前(在用户点击后)选中或未选中的项目?我搜索了 EventArgs 和发件人属性,但找不到任何东西。

感谢您的帮助

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    好的,我将代码更改为:

    if (this.checkedListBoxChannels.CheckedItems.Count == 1) {
        if (e.NewValue == CheckState.Unchecked) {
            this.btnOK.Enabled = false;
        }
    } else {
        this.btnOK.Enabled = true;
    }
    

    现在它工作正常。

    【讨论】:

      【解决方案2】:

      如果您查看 msdn 文档

      http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.itemcheck%28v=vs.110%29.aspx

      在“备注”下它说: “直到 ItemCheck 事件发生后,检查状态才会更新。” 所以它不会注册您的最后一次更改。 您还可以使用其他事件。 (可能是单击或 SelectedIndexChanged?)

      【讨论】:

        【解决方案3】:

        您可以使用 ItemCheckEventArgs 的 NewValue 属性:

         private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                if (checkedListBox1.CheckedItems.Count > 1)
                {
                    button1.Enabled = true;
                    return;
        
                }
        
                //Last Item is uncheked
                if (checkedListBox1.CheckedItems.Count == 1 && e.NewValue == CheckState.Unchecked)
                {
                    button1.Enabled = false;
                    return;
                }
        
                //First Item is checked
                if (checkedListBox1.CheckedItems.Count == 0 && e.NewValue == CheckState.Checked)
                {
                    button1.Enabled = true;
                    return;
                }
            }
        

        【讨论】:

          【解决方案4】:

          你的情况应该是

          this.checkedListBoxChannels.CheckedItems.Count > 0
          

          【讨论】:

          • 这不起作用。如果我取消选中最后一个复选框,则计数为 1,因此按钮不会被禁用。
          猜你喜欢
          • 1970-01-01
          • 2014-01-08
          • 1970-01-01
          • 1970-01-01
          • 2020-03-31
          • 1970-01-01
          • 2015-07-26
          • 1970-01-01
          相关资源
          最近更新 更多