【问题标题】:How to check all checkbox by pressing one?如何通过按一个来选中所有复选框?
【发布时间】:2018-12-11 12:00:09
【问题描述】:

我想通过从 ListView 中选择一个复选框来自动选择 ListView 中的所有复选框来编写代码。

我使用的是 Visual Studio 2005,所以我没有 ItemChecked 表单。 这就是为什么我想通过使用 ListView itemcheck 事件来做到这一点。这是我的代码。

private void lvBase_ItemCheck_1(object sender, ItemCheckEventArgs e)
{

    if ( ) // If selecting one checkbox from the ListView
    {
        for (int i = 0; i < lvBase.Items.Count; i++)
        {
         // Select all checkbox from the ListView
         }
     }
     else // If unselecting one checkbox from the ListView
     {
        for (int i = 0; i < lvBase.Items.Count; i++)
        {
         // Unselect all checkbox from the ListView
         }
     } 
}

你能帮我填写一下吗?或者如果你有更好的想法,请分享:)

【问题讨论】:

  • 您应该遍历 Items 集合并为每个集合设置 Checked 属性。
  • 感谢您的回复!我不擅长 C#,但你的意思是“lvBase.Items[i].Checked == true”吗?我不知道在“如果”中填写什么。你能帮我吗?
  • 这是一个不同的问题。查看 checkAll 或其他内容的 listview 属性 - 抱歉,我自己不确定

标签: c# winforms checkbox


【解决方案1】:

注意:很可能有更好的方法来做到这一点,但这是我很久以前使用的一种模式,并且当时有效。 :)

如果您在上面显示,它将从 listView 调用,ItemCheckEventArgs e 会告诉您该框是否已选中。它实际上会告诉您检查之前 复选框的状态。因此,如果未选中复选框而用户只是选中了它,e.CurrentValue 将是 CheckState.Unchecked

现在,如果我们尝试更新 ItemCheck 事件中所有复选框的状态,我们可能会遇到的问题是,我们每次选中一个框时都会递归调用该事件。解决此问题的一种方法是跟踪用户是否正在调用事件(通过选中一个框)或者我们是否通过调用 item.Checked = true; 来触发事件。

这样的事情可能会奏效:

// Set this to true when our code is modifying the checked state of a listbox item
private bool changingCheckboxState = false;

private void lvBase_ItemCheck(object sender, ItemCheckEventArgs e)
{
    // If our code triggered this event, just return right away
    if (changingCheckboxState) return;

    // Set our flag so that calls to this method inside the 
    // loop below don't trigger more calls to this method
    changingCheckboxState = true;

    // Set all the checkboxes to match the state of this one
    foreach(ListViewItem item in lvBase.Items)
    {
        item.Checked = e.CurrentValue != CheckState.Checked;
    }

    // Now that we're done, set our flag to false again
    changingCheckboxState = false;
}

【讨论】:

  • 有效!!感谢您分享您的知识 Rufus L :)
【解决方案2】:

使用ListViewItem.Selected 属性:

foreach(ListViewItem item in lv.Items)
    item.Selected = true;


foreach(ListViewItem item in lv.Items)
    item.Selected = !item.Selected;

【讨论】:

  • 您的意思是删除 If-else 并粘贴您的代码吗?它不起作用:(
  • 我正在显示 Checked 属性的设置。我不清楚用户是想从您的代码中选择全选还是取消全选。
  • 你能告诉我如何让ListView复选框选择代码来填写“If()”
  • 为您更新了我的答案 - 如果满意,请点击 tick 标记为已回答 - 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2015-06-15
  • 1970-01-01
相关资源
最近更新 更多